Last active
June 17, 2018 18:58
-
-
Save drenther/2e6bcf3efabf28f00986d51a3da0b332 to your computer and use it in GitHub Desktop.
UniversalDataloader.js for react-ssr
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
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