Skip to content

Instantly share code, notes, and snippets.

@acdlite
Last active August 15, 2018 04:36
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save acdlite/40944921819ae817fcb62d8084ea11b8 to your computer and use it in GitHub Desktop.
Save acdlite/40944921819ae817fcb62d8084ea11b8 to your computer and use it in GitHub Desktop.
Idea for Dataloader component
// The `loader` prop is a Dataloader instance
// https://github.com/facebook/dataloader
class Dataloader extends React.Component {
state = {data: null, isLoaded: false};
componentWillMount() {
this.prefetchData(this.props);
}
componentWillReceiveProps(nextProps) {
if (this.props.id !== nextProps.id || this.props.loader !== nextProps.loader) {
this.setState({isLoaded: false});
this.prefetchData(nextProps);
}
}
async prefetchData(props) {
const data = await props.loader.load(props.id);
this.setState({data, isLoaded: true});
}
render() {
return this.props.render(this.state.data, this.state.isLoaded);
}
}
// TODO: Support for loader.loadMany, loader.clear
function PostContainer {
return (
<Dataloader
loader={postLoader}
id="123"
render={(post, isLoaded) => {
if (!isLoaded) {
return <Spinner />;
}
return <Post post={post} />;
}}
/>;
);
}
@dani-mp
Copy link

dani-mp commented Sep 20, 2017

I'm also confused about it because of this Dan's SO answer and the React docs about cWM and cDM, so not sure what to do in a case like this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment