Skip to content

Instantly share code, notes, and snippets.

@ShMcK
Created July 1, 2018 16:20
Show Gist options
  • Save ShMcK/c82b0e0e07090cb2ae5312d79f8d5071 to your computer and use it in GitHub Desktop.
Save ShMcK/c82b0e0e07090cb2ae5312d79f8d5071 to your computer and use it in GitHub Desktop.
VisualizingState: State !== Data
type States = {
 mode: 'loading' | 'loaded' | 'error',
 data: any,
}
class DataLoader extends React.Component<{}, States> {
 state = {
  mode: 'loading', // state
  data: {}, // data
 }
 componentDidMount() {
  this.props.load()
  .then(({ data, error }) => {
  if (!error) {
  this.setState({ mode: 'loaded', data })
  } else {
  this.setState({ mode: 'error', data: error })
  }
  })
 }
 render() {
  const { mode, data } = this.state
  switch(mode) {
  case 'loading':
  return <Loading />
 case 'loaded':
  return <Loaded data={data} />
  default:
  return <Error data={data} />
  }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment