redux-async-fetcher
v2.0.0
Published
Extract data fetching logic from your component lifecycle
Downloads
5
Maintainers
Readme
Redux-Async-Fetcher
ReduxAsyncFetcher is used to extract data fetching logic from your component lifecycle.
Installation
npm install --save redux-async-fetcher
Documentation
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(asyncDataFetch, [propsToWatch])(NormalComponent)
Arguments
asyncDataFetch
(Function): Function that will be called atNormalComponent
componentDidMount hook.propsToWatch
(Array): Default value: []. Array of props name that will triggerasyncDataFetch
atNormalComponent
componentDidUpdate hook if shallow comparison between propsToWatch lastProps and props is false.
Usage
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 asyncDataFetch
and precise propsToWatch
names if you want to retrigger your data fetching on some props change.
asyncDataFetch
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 asyncDataFetch = (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())
}
In the wild
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 asyncDataFetch = (dispatch, props, state) => {
if (state.users.indexOf(props.userId) === -1)
dispatch(getUser(props.userId))
}
export default withRouter(
connect(mapStateToProps, mapDispatchToProps)(
reduxAsyncFetcher(getAsyncState, ['userId'])(UserView)))
Change Log
This project adheres to Semantic Versioning.
You can find every release documented on the Releases page.
License
MIT