'i cant control userReducer actions in context
i try to use useReducer. First of all i try to pass dispatch as a props for getting global state for parent component states. so it's became so confusing and uncontrollable. So i have an idea. what if i create a context inside useReducer and get dispatch event without passing as a props. bu when i do that it returns always initial state and not dispatching any actions.
const AuthContext = createContext({
state: {},
dispatch:() => {}
});
export const AuthReducerProvider = ({ children }) => {
const [state, dispatch] = useReducer(authReducer);
const contextValue = useMemo(() => ({ state, dispatch }), [state, dispatch]);
return <AuthContext.Provider value={contextValue}>{children}</AuthContext.Provider>;
};
export const useAuthReducerContext = () => {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error(`error`);
}
return context;
};
i wrap my component with AuthReducerProvider. but when i try to import useAuthReducerContext and run dispatch function it's always return as initialValues.
actually my questions is
1- is it an good idea? :D
2- or did a do something wrong
Solution 1:[1]
The code you posted is pretty standard, there's nothing wrong with it. Probably, something else is causing your issue.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mirco Bellagamba |
