Skip to content

Instantly share code, notes, and snippets.

@julianburr
Last active August 27, 2019 09:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save julianburr/8570491198f80b3af409dbb93b1d31c0 to your computer and use it in GitHub Desktop.
Save julianburr/8570491198f80b3af409dbb93b1d31c0 to your computer and use it in GitHub Desktop.
Why Suspense Will Be a Game Changer - Context
const DataContext = React.createContext();
class DataContextProvider extends Component {
// We want to be able to store multiple sources in the provider,
// so we store an object with unique keys for each data set +
// loading state
state = {
data: {},
fetch: this.fetch.bind(this)
};
fetch (key) {
if (this.state[key] && (this.state[key].data || this.state[key].loading)) {
// Data is either already loaded or loading, so no need to fetch!
return;
}
this.setState(
{
[key]: {
loading: true,
error: null,
data: null
}
},
() => {
fetchData(key)
.then((data) => {
this.setState({
[key]: {
loading: false,
data
}
});
})
.catch((e) => {
this.setState({
[key]: {
loading: false,
error: e.message
}
});
});
}
);
}
render () {
return <DataContext.Provider value={this.state} {...this.props} />;
}
}
class DynamicData extends Component {
static contextType = DataContext;
componentDidMount () {
this.context.fetch(this.props.id);
}
componentDidUpdate (prevProps) {
if (this.props.id !== prevProps.id) {
this.context.fetch(this.props.id);
}
}
render () {
const { id } = this.props;
const { data } = this.context;
const idData = data[id];
return idData.loading ? (
<p>Loading...</p>
) : idData.error ? (
<p>Error: {idData.error}</p>
) : (
<p>Data loaded 🎉</p>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment