-
-
Save ksmandersen/ae3178361c3f2839ce49f1d934c48f78 to your computer and use it in GitHub Desktop.
Simple HOC for fetching data that is compatible with the SSR technique described by @BenLu here: https://medium.com/@benlu/ssr-with-create-react-app-v2-1-ee83fb767327
This file contains hidden or 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 React from 'react'; | |
const hasDataForKey = (staticContext) => (key) => staticContext && Object.keys(staticContext.data).includes(key); | |
const windowHasDataForKey = (window) => (key) => Object.keys(window.__DATA__).includes(key); | |
export default ({ key, prop, getData }) => (WrappedComponent) => { | |
class SSRCompatibleComponent extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = {}; | |
} | |
async componentWillMount() { | |
this._handleData(); | |
} | |
async _handleData() { | |
const { staticContext } = this.props; | |
if (hasDataForKey(staticContext)(key)) { | |
const data = staticContext.data[key]; | |
this._setData(data); | |
} else if (staticContext) { | |
staticContext[key] = this._getData(); | |
} else if (!staticContext && windowHasDataForKey(window)(key)) { | |
const data = window.__DATA__[key]; | |
window.__DATA__[key] = null; | |
this._setData(data); | |
} else if (!staticContext) { | |
const data = await this._getData(); | |
this._setData(data); | |
} | |
} | |
_setData(data) { | |
this.setState({ ...this.state, [prop]: data }); | |
} | |
async _getData() { | |
const { props } = this; | |
const { data } = await getData({ props }); | |
return data; | |
} | |
render() { | |
return <WrappedComponent {...this.props} {...this.state} />; | |
} | |
} | |
return SSRCompatibleComponent; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment