Skip to content

Instantly share code, notes, and snippets.

@drenther
Last active June 17, 2018 18:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drenther/2e6bcf3efabf28f00986d51a3da0b332 to your computer and use it in GitHub Desktop.
Save drenther/2e6bcf3efabf28f00986d51a3da0b332 to your computer and use it in GitHub Desktop.
UniversalDataloader.js for react-ssr
import { Component } from 'react';
class UniversalDataloader extends Component {
constructor(props) {
super(props);
let data;
if (__isBrowser__ && window.__SERIALIZED_DATA__) {
data = window.__SERIALIZED_DATA__;
delete window.__SERIALIZED_DATA__;
} else if (this.props.staticContext) {
data = this.props.staticContext.data;
}
this.state = {
data,
loading: data ? false : true,
};
}
componentDidMount() {
if (!this.state.data) {
this.fetchData(this.props.match.params.id);
}
}
fetchData = id => {
this.setState({ loading: true });
this.props.getInitialData(id).then(data => {
this.setState({ data, loading: false });
});
};
render() {
return this.props.children(this.state);
}
}
export default UniversalDataloader;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment