Skip to content

Instantly share code, notes, and snippets.

@ksmandersen
Forked from armand1m/withInitialData.js
Last active February 8, 2018 19:52
Show Gist options
  • Save ksmandersen/ae3178361c3f2839ce49f1d934c48f78 to your computer and use it in GitHub Desktop.
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
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