redux-pact
v0.1.0
Published
Utilities for dealing with simple promise-based side effects in action creators.
Downloads
4
Readme
Redux Pact
Utilities for dealing with simple promise-based side effects in action creators.
When writing action creators in Redux, it's good to keep them as simple as possible:
const buttonWasClicked = () => ({ type: 'BUTTON_WAS_CLICKED' })
but real life is not that simple, and a lot of the time you need to involve nasty impure things when thinking about state. This may be needing to talk to a server, or some other kind of asyncronous process. This is an example of a side effect; an process that occurs in the course of a state transition that is 'impure' and unpredicable.
A simple way to contain these async side effects in redux is to use redux-thunk; in a nutshell this middleware lets you turn a simple acion creator from a function that returns an object, into a function that returns a function that dispatches many objects over time:
const loadUser = id => dispatch => {
dispatch({ type: 'LOAD_USER_REQUESTED' })
fetch(`/users/${id}`)
.then(resp => resp.json())
.then(data => serializeUser(data))
.then(user => dispatch({ type: 'LOAD_USER_COMPLETE', payload: user }))
.catch(e => dispatch({ type: 'LOAD_USER_FAILED', error: true, payload: e }))
}
you can then respond to each of these action types accordingly in your reducer. This is a desirable way to work, because you have a lot of power; you can dispatch whatever you want whenever you want!
But with great power comes great responsibility and generally speaking reducing your power in any given place in your code will also reduce your ability to mess things up.
Redux Pact is an intentially small set of utilities to help reduce your power when dealing with async side effects in action creators.
Usage
Prerequisites
These utilities require you to be using redux, and have the redux-thunk middleware installed.
Installation
npm install --save redux-pact
or
yarn add redux-pact
makeAction
You can use the makeAction
utility to replace your action creator functions:
import { makeAction } from 'redux-pact'
const actionType = 'FETCH_USER'
const fetchUser = id => fetch(`/users/${id}`).then(convertFromJson).then(serialiseUser)
const requestUserAction = makeAction(actionType, fetchUser)
dispatch(requestUserAction(23))
you can then use helper utilities in your reducers:
import { actionInspectors } from 'redux-pact'
const actionType = 'FETCH_USER'
const { isBusy, isSuccess, isFailure } = actionInspectors(actionType)
export default (state = {}, action = {}) => {
if (isBusy(action)) {
return { ...state, busy: true, error: undefined }
}
if (isSuccess(action)) {
return { ...state, busy: false, error: undefined, data: action.payload }
}
if (isFailure(action)) {
return { ...state, busy: false, error: action.payload.message }
}
return state
}
basicReducer
The reducer described above is pretty generic - you can actually use the bundled basic reducer if you wish:
import { basicReducer } from 'redux-pact'
const actionType = 'FETCH_USER'
export default basicReducer(actionType)
This is obviously less flexible, but that's sort of the point isn't it :)
API
makeAction(actionType: string, makePromise: (args) => Promise, {finally: Function}): ActionCreatorFunction
The makeAction
utility takes in an action type (should be string) and a reference to a function that will return a promise.
The function can take whatever arguments it needs to create the promise; these arguments will be the arguments of the action creator that makeAction
will return. The resulting Action Creator Function can be passed to redux's dispatch providing you have the redux-thunk middleware installed
You can optionally pass a function to run in the promise chain's finally
handler, which will execute even if there is an error. This can be useful if you want to log to analytics each time a promise is attempted, for example.
actionInspectors(actionType: string): { isBusy, isSuccess, isFailure }
You can use this utility to check if an action is a busy action, a success action or a failure action. The utility is meant to be used in your reducers to match actions and are FSA-compliant.
const { isBusy, isSuccess, isFailure } = actionInspectors(actionType)
isBusy(action) // will return true if action is a 'busy action'
isSuccess(action) // will return true if action is a 'success action'
isFailure(action) // will return true if action is a 'failure action'
as we're talking about actions, this is what actions look like:
const action = {
type: 'FETCH_USER', // this is the action type string that you provide
error: false, // if the action is a failure, then this is true
payload: { id: 23 }, // the contents of payload is the last value returned in
// your promise chain. If the action is a failure then
// this is the error object from the promise's 'catch'
meta: {
busy: false, // if the action is busy, this is true
args: [23] // this is a copy of the arguments provided to the action
}
}
basicReducer(actionType: string, {defaultErrorMessage: string})
This utility will provide you a basic redux reduce that you can compose with redux's combineReducers if you like. You need to provide it the action type string so it knows what action to match to. By default if the reducer cannot find an error message in the error object provided by your promise, it will use the string passed in the optional config, which by default is 'An Error Occurred'
.