I have an application without redux, I handle the global state with hooks and the hook useReducer + context. I have 1 useReducer which makes like a Redux store. But to do this I can only send 1 reducer. In that reducer I have all the logic of the states, but I want to separate some functions of that reduce in other reducers. In redux there is the combineReducer to do this. But with hooks + context, how can I do this? How do I combine many reducers to send it to my Global Provider in the useReducer?
//Global Provider
const [state, dispatch] = useReducer(reducer, {
isAuthenticated: null,
user: {},
catSelect: 10,
productsCart,
total
});
//reducer with all cases
export default function(state , action ){
switch(action.type) {
case SET_CURRENT_USER:
return etc...
case SET_CATEGORIA:
return etc...
case 'addCart':
return etc...
case etc....
default:
return state;
}
}
for now this works. But the reducer contains "cases" that do completely different things than other "cases". For example a "case" for authentication, another "case" to add products, another "case" to eliminate suppliers, etc.
With Redux I would have created more reducers (auth, shopCart, suppliers, etc) and use the combineReducer to control all that.
Without Redux I have to have everything mixed in 1 just reduce. So that I need, a combineReducer to combine many different reducers, or some other way of doing all this with Hooks + context
I have been developing a bit of a boilerplate with this use case. this is how I am currently doing it.
Provider.js
import appReducer from "./reducers/app";
import OtherAppReducer from "./reducers/otherApp";
export const AppContext = createContext({});
const Provider = props => {
const [appState, appDispatch] = useReducer(appReducer, {
Thing: []
});
const [otherAppState, otherAppDispatch] = useReducer(OtherAppReducer, {
anotherThing: []
});
return (
<AppContext.Provider
value={{
state: {
...appState,
...otherAppState
},
dispatch: { appDispatch, otherAppDispatch }
}}
>
{props.children}
</AppContext.Provider>
);
};
Reducer.js
const initialState = {};
export default (state = initialState, action) => {
switch (action.type) {
case "action":
return {
...state
};
default:
return state;
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With