Last active
August 15, 2018 04:36
-
-
Save acdlite/40944921819ae817fcb62d8084ea11b8 to your computer and use it in GitHub Desktop.
Idea for Dataloader component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function PostContainer { | |
return ( | |
<Dataloader | |
loader={postLoader} | |
id="123" | |
render={(post, isLoaded) => { | |
if (!isLoaded) { | |
return <Spinner />; | |
} | |
return <Post post={post} />; | |
}} | |
/>; | |
); | |
} |
Fixed
Also, an async setState
is fine in componentWillMount
. It's actually the primary use case: initiating a data request as early as possible.
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)
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
I thought setting state in cWM was a no no?