-
-
Save ksmandersen/1a067ea0cd71e9fa6b5d48ea4c2d5e21 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 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, { Component } from 'react'; | |
const hasDataForThisKey = (staticContext) => | |
(key) => staticContext && Object.keys(staticContext.data).includes(key); | |
const windowHasDataForThisKey = (window) => | |
(key) => Object.keys(window.__DATA__).includes(key); | |
export default ({ | |
key, | |
prop, | |
getData, | |
}) => (WrappedComponent) => { | |
class SSRCompatibleComponent extends Component { | |
constructor(props) { | |
super(props); | |
this.state = {}; | |
} | |
async componentWillMount() { | |
this._handleData(); | |
} | |
async _handleData() { | |
const { staticContext } = this.props; | |
if (hasDataForThisKey(staticContext)(key)) { | |
const data = staticContext.data[key]; | |
this._setData(data); | |
} else if (staticContext) { | |
staticContext.data[key] = this._getData(); | |
} else if (!staticContext && windowHasDataForThisKey(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