-
-
Save namuol/ead16c7428fec654e1cd8bf30f76cbda 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` argument is a Dataloader instance | |
// https://github.com/facebook/dataloader | |
const makeLoader = (loader) => { | |
class Dataloader extends React.Component { | |
state = {data: null, isLoaded: false}; | |
componentWillMount() { | |
this.prefetchData(this.props); | |
} | |
componentWillReceiveProps(nextProps) { | |
if (this.props.id !== nextProps.id) { | |
this.setState({isLoaded: false}); | |
this.prefetchData(nextProps); | |
} | |
} | |
async prefetchData(props) { | |
const data = await loader.load(props.id); | |
this.setState({data, isLoaded: true}); | |
} | |
render() { | |
return this.props.render(this.state.data, this.state.isLoaded); | |
} | |
} | |
return Dataloader; | |
}; | |
// 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
const Postloader = makeLoader(postLoader); | |
function PostContainer { | |
return ( | |
<Postloader | |
id="123" | |
render={(post, isLoaded) => { | |
if (!isLoaded) { | |
return <Spinner />; | |
} | |
return <Post post={post} />; | |
}} | |
/>; | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment