Created
November 13, 2015 16:36
-
-
Save timdorr/3ffe30e3c4e116019bc3 to your computer and use it in GitHub Desktop.
Prefetching Data Decorator
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, { 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