Skip to content

Instantly share code, notes, and snippets.

@julianburr
Last active January 20, 2019 02:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save julianburr/2ab30be942268ca86d4ac016de85abc5 to your computer and use it in GitHub Desktop.
Save julianburr/2ab30be942268ca86d4ac016de85abc5 to your computer and use it in GitHub Desktop.
Why Suspense Will Be a Game Changer - Local State
class DynamicData extends Component {
state = {
loading: true,
error: null,
data: null
};
componentDidMount () {
fetchData(this.props.id)
.then((data) => {
this.setState({
loading: false,
data
});
})
.catch((error) => {
this.setState({
loading: false,
error: error.message
});
});
}
componentDidUpdate (prevProps) {
if (this.props.id !== prevProps.id) {
this.setState({ loading: true }, () => {
fetchData(this.props.id)
.then((data) => {
this.setState({
loading: false,
data
});
})
.catch((error) => {
this.setState({
loading: false,
error: error.message
});
});
});
}
}
render () {
const { loading, error, data } = this.state;
return loading ? (
<p>Loading...</p>
) : error ? (
<p>Error: {error}</p>
) : (
<p>Data loaded 🎉</p>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment