Skip to content

Instantly share code, notes, and snippets.

@timdorr
Created November 13, 2015 16:36
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timdorr/3ffe30e3c4e116019bc3 to your computer and use it in GitHub Desktop.
Save timdorr/3ffe30e3c4e116019bc3 to your computer and use it in GitHub Desktop.
Prefetching Data Decorator
import React, { Component, PropTypes } from 'react';
import hoistStatics from 'hoist-non-react-statics';
const { shape, func } = PropTypes;
let initialRender = true;
export function rendered() {
initialRender = false;
}
export default (fetch) => {
return WrappedComponent => {
class FetchDataDecorator extends Component {
static WrappedComponent = WrappedComponent;
static fetchData = fetch;
static contextTypes = {
store: shape({
subscribe: func.isRequired,
dispatch: func.isRequired,
getState: func.isRequired
})
};
componentDidMount() {
if (initialRender) return;
const { getState, dispatch } = this.context.store;
fetch(getState(), dispatch);
}
render() {
return <WrappedComponent {...this.props} />;
}
}
return hoistStatics(FetchDataDecorator, WrappedComponent)
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment