Last active
October 19, 2015 20:33
-
-
Save grrowl/6cca2162e468891d8128 to your computer and use it in GitHub Desktop.
redux and react-router helper to provide (dispatch, storeState) to a static fetchData method
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
'use strict'; | |
/* | |
# FetchData | |
If property callback `if(storeState)` return true, calls property callback | |
`fetchData(dispatch, storeState)` so it may dispatch FETCH actions. | |
## Usage: | |
`<FetchData fetchData={ MyComponent.fetchData } if={ this.shouldFetchData } />` | |
Only checks on componentDidMount (which doesn't run on server/ | |
React.renderToString). Still, throttling is left to the responsibility of the | |
parent component. | |
## Context: | |
This allows us to call the same static `fetchData` method used to assist server | |
rendering (as described in this react-router issue: | |
<https://github.com/rackt/react-router/issues/57>) on the client, with correct | |
references to dispatch and state (to dispatch asynchronous `_FETCH` actions). | |
*/ | |
import React, { PropTypes } from 'react'; | |
import invariant from 'invariant'; | |
export default class FetchDataConnector extends React.Component { | |
shouldComponentUpdate(nextProps, nextState) { | |
return false; | |
} | |
// componentDidMount is only called on the client, not during server renders | |
componentDidMount() { | |
this.checkIf(this.props, this.context); | |
} | |
// If `if` callback returns truthy, call `fetchData` callback | |
checkIf(props, context) { | |
const dispatch = context.store.dispatch; | |
const state = context.store.getState(); | |
if (props.if(state)) { | |
props.fetchData(dispatch, state); | |
} | |
} | |
// Should not render children. | |
render() { | |
return null; | |
} | |
} | |
// const storeShape = createStoreShape(PropTypes); | |
FetchDataConnector.contextTypes = { | |
// store: storeShape.isRequired | |
store: PropTypes.object.isRequired | |
}; | |
FetchDataConnector.propTypes = { | |
fetchData: PropTypes.func.isRequired, | |
if: PropTypes.func.isRequired | |
}; | |
FetchDataConnector.defaultProps = { | |
fetchData: (dispatch, state) => false, | |
if: state => false | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment