Redux Capture
Captures all the actions dispatched by sync or async thunk actions.
Installation
npm install redux-capture
Motivation
Suppose we have an async thunk action that fetches data and dispatches it as FSA compliant action:
const WILL_FETCH_DATA = 'WILL_FETCH_DATA'const DID_FETCH_DATA = 'DID_FETCH_DATA' { return async { // Notify that we are fetching data try const response = await if !responseok throw `Failed to fetch with status ` // Dispatch the data as action payload. catch error // Dispatch an error action if it failed to do so. }}
And we want isFetching
state as follows:
const defaultState = counter: 0 isFetching: false const reducer =
This will work as it’s supposed to. The counter
will increment as fetchData
are dispatched and decrement as they finish, changing isFetching
to correct values.
In many cases, we want to make other actions that rely on such actions like fetchData
, so to reuse its state transitions. Redux Capture allows you to capture actions dispatched by thunk actions.
const FETCH_USERS = 'FETCH_USERS'const FETCH_GUESTS = 'FETCH_GUESTS' { return async { try // This will be payload of the last action dispatched by fetchData, or // throw error if it’s an error action. const data = await catch error }} { return async { try // Same discussion above. This capture returns users. const users = await catch error }}
Or capture the last action itself or all the actions when FSA is not your preference.
const lastAction = await // { type: FETCH_USERS, ... } const actions = await // [// { type: WILL_FETCH_DATA, ... },// { type: DID_FETCH_DATA, ... },// { type: FETCH_USERS, ... }// ]
API Reference
capture(action, dispatch [, getState])
action
: object | functiondispatch
: functiongetState
: (Optional) function
When action
is an action object, this returns its payload
. Throws payload
if its error
is true.
When action
is a sync thunk action, this returns its payload
of the last action dispatched by it. Throws payload
if error
of the last action is true.
When action
is an async thunk action, this returns Promise that resolves payload
of the last action, or rejects with payload
if error
of the last action is true.
captureLastAction(action, dispatch [, getState])
action
: object | functiondispatch
: functiongetState
: (Optional) function
Returns the last action dispatched by action
, or Promise that resolves it.
captureActions(action, dispatch [, getState])
action
: object | functiondispatch
: functiongetState
: (Optional) function
Returns an array of all the actions dispatched by action
, or Promise that resolves it.
License
MIT