UNPKG

use-async-reducer

Version:

Provides a reducer to simplify handling of async actions

64 lines 2.28 kB
import { useReducer, useCallback } from 'react'; import { getType } from 'typesafe-actions'; import * as actions from './actions'; export * from './actions'; export * from './constants'; export const reducer = (state, action) => { switch (action.type) { case getType(actions.initialize): return { data: null, loading: true, error: null }; case getType(actions.request): return { ...state, error: null, loading: true }; case getType(actions.success): return { data: action.payload, error: null, loading: false }; case getType(actions.failure): return { data: null, error: action.payload, loading: false }; case getType(actions.complete): return { ...state, loading: false }; /* istanbul ignore next */ default: return state; } }; /** * Provides a reducer and actions to manage states of async operations * @param initialValue Will set the `data` attribute of the first returned value * @returns An array of two values * 0. the state of the async operation with the shape * 1. object of bound action methods * * @see [https://github.com/azmenak/use-async-reducer/blob/master/README.md](https://github.com/azmenak/use-async-reducer/blob/master/README.md) */ export default function useAsyncReducer(initialValue) { const [state, dispatch] = useReducer(reducer, { data: initialValue || null, loading: false, error: null }); const initialize = useCallback(() => dispatch(actions.initialize()), []); const request = useCallback(() => dispatch(actions.request()), []); const success = useCallback((payload) => dispatch(actions.success(payload)), []); const failure = useCallback((error) => dispatch(actions.failure(error)), []); const complete = useCallback(() => dispatch(actions.complete()), []); return [state, { initialize, request, success, failure, complete }]; } //# sourceMappingURL=index.js.map