Nov 12, 2022
0
Level 2
useReducer not updating the state inside context provider in NextJs 13
useReducer inside context provider is only returning the initial state instead of updated state after dispatching and running reducer function.
When I console log the action inside reducer function, developer console logs the action object that I passed but it is not updated in the return of if statement.
GlobalContext.js
import { createContext } from 'react';
const GlobalContext = createContext({
auth: {
user: Object,
token: String,
addUserData: Function,
},
});
export default GlobalContext;
GlobalProvider.js
import { useReducer } from 'react';
import GlobalContext from './GlobalContext';
const initState = {
auth: {
user: {},
token: null,
},
};
const reducer = (state, action) => {
if (action.type === 'ADD_USER_DATA') {
console.log(action);
return {
...state,
auth: {
user: 'user',
token: 'token',
},
};
}
};
const GlobalProvider = ({ children }) => {
const [state, dispatch] = useReducer(reducer, initState);
const value = {
auth: {
user: state.auth.user,
token: state.auth.token,
addUserData: (user, token) => {
dispatch({ type: 'ADD_USER_DATA', payload: { user, token } });
},
},
};
return (
<GlobalContext.Provider value={value}>{children}</GlobalContext.Provider>
);
};
export default GlobalProvider;
Please or to participate in this conversation.