- Notifications
You must be signed in to change notification settings - Fork9
React useReducer with async actions
License
dai-shi/use-reducer-async
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
React useReducer with async actions
React useReducer doesn't support async actions natively.Unlike Redux, there's no middleware interface, but hooks are composable.
This is a tiny library to extend useReducer's dispatchso that dispatching async actions invoke async functions.
npm install use-reducer-async
import{useReducerAsync}from"use-reducer-async";constinitialState={sleeping:false,};constreducer=(state,action)=>{switch(action.type){case'START_SLEEP':return{ ...state,sleeping:true};case'END_SLEEP':return{ ...state,sleeping:false};default:thrownewError('no such action type');}};constasyncActionHandlers={SLEEP:({ dispatch})=>async(action)=>{dispatch({type:'START_SLEEP'});awaitnewPromise(r=>setTimeout(r,action.ms));dispatch({type:'END_SLEEP'});},};constComponent=()=>{const[state,dispatch]=useReducerAsync(reducer,initialState,asyncActionHandlers);return(<div><span>{state.sleeping ?'Sleeping' :'Idle'}</span><buttontype="button"onClick={()=>dispatch({type:'SLEEP',ms:1000})}>Click</button></div>);};
All async action handlers receivesignal in the argument.Referexamples/04_abort/src for the usage.
Note: The implementation depends onAbortController in the DOM spec.If you are using an environment that doesn't have AbortController (for example IE11), you need a polyfill:12
useReducer with async actions
reducerRinitialStateReducerState<R>asyncActionHandlersAsyncActionHandlers<R, AsyncAction>
import{useReducerAsync}from'use-reducer-async';constasyncActionHandlers={SLEEP:({ dispatch, getState, signal})=>async(action)=>{dispatch({type:'START_SLEEP'});awaitnewPromise(r=>setTimeout(r,action.ms));dispatch({type:'END_SLEEP'});},FETCH:({ dispatch, getState, signal})=>async(action)=>{dispatch({type:'START_FETCH'});try{constresponse=awaitfetch(action.url);constdata=awaitresponse.json();dispatch({type:'FINISH_FETCH', data});}catch(error){dispatch({type:'ERROR_FETCH', error});}},};const[state,dispatch]=useReducerAsync(reducer,initialState,asyncActionHandlers);
Returns[ReducerState<R>, Dispatch<ExportAction>]
Theexamples folder contains working examples.You can run one of them with
PORT=8080 npm run examples:01_minimal
and openhttp://localhost:8080 in your web browser.
About
React useReducer with async actions
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors4
Uh oh!
There was an error while loading.Please reload this page.