Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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} />;
}}
/>;
);
}
@acdlite

This comment has been minimized.

Copy link
Owner Author

@acdlite acdlite commented Sep 20, 2017

If you render multiple Dataloader components, it'll batch together all the ids and send them to the server as a single request. Yay!

@acdlite

This comment has been minimized.

Copy link
Owner Author

@acdlite acdlite commented Sep 20, 2017

See https://github.com/facebook/dataloader for more details on how that works. It's a really nice API.

Obviously, this isn't as powerful as GraphQL/Relay/Apollo, but it's simple and works with most backends.

@jaredpalmer

This comment has been minimized.

Copy link

@jaredpalmer jaredpalmer commented Sep 20, 2017

I thought setting state in cWM was a no no?

@acdlite

This comment has been minimized.

Copy link
Owner Author

@acdlite acdlite commented Sep 20, 2017

Fixed

@acdlite

This comment has been minimized.

Copy link
Owner Author

@acdlite acdlite commented Sep 20, 2017

Also, an async setState is fine in componentWillMount. It's actually the primary use case: initiating a data request as early as possible.

@rostero1

This comment has been minimized.

Copy link

@rostero1 rostero1 commented Sep 20, 2017

I've been programmed to think no setState in cWM and had no idea it was ok if async. Glad I checked this out. And nice idea.

(I also don't even think ReasonReact supports cWM, but could be wrong)

@dani-mp

This comment has been minimized.

Copy link

@dani-mp 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