react-context-simply
Advanced tools
Comparing version 1.0.1 to 1.0.2
15
index.js
@@ -5,11 +5,12 @@ import React, { createContext, useContext, useReducer, useCallback } from 'react'; | ||
export default function createStateContext(initialState, reducer, actions, middleware) { | ||
const middlewares = Array.isArray(middleware) ? middleware : [middleware] | ||
const middlewares = Array.isArray(middleware) ? middleware : (middleware && [middleware]) | ||
const StateContext = createContext([initialState, () => null]); | ||
const StateProvider = ({children}) => { | ||
const [state, dispatch] = middlewares.reduce((result, mw) => { | ||
const [st, agg] = useReducer(reducer, initialState) | ||
const chain = [] | ||
const [state, dispatch] = middlewares ? middlewares.reduce(([st, agg], mw) => { | ||
const newDis = action => { | ||
const types = Array.isArray(mw.action) ? mw.action : [mw.action] | ||
if(types.includes(action.type) || types.includes('*')){ | ||
return mw ? mw.middleware([st, agg]) : agg | ||
let [_, next] = mw.middleware([state, agg]) | ||
return next(action) | ||
}else{ | ||
@@ -19,5 +20,7 @@ return agg(action) | ||
} | ||
chain.push(newDis) | ||
return [st, newDis] | ||
}, []); | ||
const enhancedDispatch = augmentDispatch(state, dispatch) | ||
}, useReducer(reducer, initialState)) : useReducer(reducer, initialState) | ||
const composedDispatch = chain.length > 0 ? chain.reduce((result, next) => async (action) => action && await result(await next(action)), dispatch) : dispatch | ||
const enhancedDispatch = augmentDispatch(state, composedDispatch) | ||
const newActions = Object.keys(actions).reduce((result, action) => { | ||
@@ -24,0 +27,0 @@ result[action] = useCallback((payload) => enhancedDispatch(actions[action](payload)), []) |
{ | ||
"name": "react-context-simply", | ||
"version": "1.0.1", | ||
"version": "1.0.2", | ||
"description": "leveraging the react context api for state management with no boilerplate code", | ||
@@ -5,0 +5,0 @@ "main": "index.js", |
2770
30