You signed in with another tab or window.Reload to refresh your session.You signed out in another tab or window.Reload to refresh your session.You switched accounts on another tab or window.Reload to refresh your session.Dismiss alert
redux-struct is a toolset to keep and update async data state in Redux store when working with REST APIs. It also drastically reduces boilerplate actions and reducers when working with such APIs.
One struct is a piece of store incapsulating fetching state, data and error from one endpoint. They are referred by string ids — for example, order with id15 can be kept under struct idorder/15. Structs are initiated automatically when the first action with given id is dispatched.
All structs have the same initial structure:
{isFetching:false,data:null,error:null,}
redux-struct provides set of action creators to start fetching data on struct with given id, stop it with result or error, update or reset it. There is also a selector to get struct by its id.
There is no built-in async middleware,redux-struct is just a data level abstraction to keep all async stuff organized.
Installation
$ npm i redux-struct
Usage
Addredux-struct reducer to your root reducer:
import{combineReducers}from'redux';import{reducerasstruct}from'redux-struct';constrootReducer=combineReducers({ struct,// other reducers});
Make an async wrapper forredux-struct actions. Implementation depends from tool you choose to maintain side effects in Redux. Here is example forredux-saga:
Selector, gets struct by name. Will return default struct if nothing was found. Has optional second argumentgetStructState() that is used to select the mount point of theredux-struct reducer from the root Redux reducer. It defaults tostate => state.struct.
startStructFetch(structId:String)
Action creator, sets structsisFetching totrue anderror tonull. Ignores other fields.
stopStructFetch(structId:String, payload:any)
Action creator, sets structsisFetching tofalse. If payload is instance ofError, setserror to payload and keep thedata. Otherwise setsdata to payload anderror tonull.
updateStruct(structId:String, payload:any)
Action creator, merges struct with payload.
resetStruct(structId:String)
Action creator, resets struct to its default state.
About
Toolset to keep and update async data state in Redux store when working with REST APIs