ReduxAsyncFetcher is used to extract data fetching logic from your component lifecycle.
npm install --save redux-async-fetcher
ReduxAsyncFetcher makes the assumption that you are using Redux to manage your React state and that you use React-Redux Provider to connect your store to your component.
ReduxAsyncFetcher takes a data fetching function as parameter and returns a Higher Order Component; by giving it a component, it will return an enhanced component.
const EnhancedComponent = reduxAsyncFetcher(getAsyncState, [propsToWatch])(NormalComponent)
getAsyncState
(Function): Function that will be called atNormalComponent
componentDidMount hook.propsToWatch
(Array): Default value: []. Array of props name that will triggergetAsyncState
atNormalComponent
componentDidUpdate hook if shallow comparison between propsToWatch lastProps and props is false.
Pass to EnhancedComponent the props you wish to convey to your NormalComponent.
const normalComponentProps = {
title: 'ReactAsyncFetcher is cool',
color: 'red',
}
<EnhancedComponent {...normalComponentProps} />
Put code that fetch data in the getAsyncState
and precise propsToWatch
names if you want to retrigger your data fetching on some props change.
getAsyncState
is called three parameters: dispatch, props and the state of the store.
// dispatch & state are taken from our Redux store (Hence the Provider dependency)
const getAsyncState = (dispatch, props, state) => {
// Here I can trigger my Redux actions like I would normally do from my NormalComponent
// I can use some logic with props & state
if (state.todoList.length === 0)
dispatch(getTodoList())
}
When you separate your component into Presentational and Container components, ReduxAsyncFetcher perfectly fit into your container components.
import { connect } from 'react-redux'
import { withRouter } from 'react-router-dom'
import reduxAsyncFetcher from 'redux-async-fetcher'
import UserView from './UserPresentational'
import { getUser, editUser } from '../../../actionCreators/users'
const mapStateToProps = (state, ownProps) => ({
users: state.users,
// Example with router parameter
userId: ownProps.match.params.userId,
})
const mapDispatchToProps = (dispatch, ownProps) => ({
editUser: user => dispatch(editUser(ownProps.match.params.userId, user)),
})
const getAsyncState = (dispatch, props, state) => {
if (state.users.indexOf(props.userId) === -1)
dispatch(getUser(props.userId))
}
export default withRouter(
connect(mapStateToProps, mapDispatchToProps)(
reduxAsyncFetcher(getAsyncState, ['userId'])(UserView)))
This project adheres to Semantic Versioning.
You can find every release documented on the Releases page.
MIT