I try to update my global state using Redux, but I try to update just one paramter of five, not all.
My store code looks like:
const initialState = { loggedIn: false, thisUser: {} } export function usersReducer(state = initialState, action) { switch (action.type) { case 'users/loggedIn': return { ...state, loggedIn: action.payload } case 'users/addUser': return { ...state, thisUser: action.payload } default: return state } }
I tried to write a new case like, but doesn’t work:
case 'users/setActivated': return { ...state, thisUser.activated: action.payload }
VS Code doesn’t let me write that “.activated”
My dispatch look like:
dispatch({ type: 'users/setActivated', payload: 1 })
What is wrong?
Advertisement
Answer
I understand why you did this, it seemed logical to you, but it will not work.
const state = { ...state, [thisUser.activated]: action.payload };
So your goal is to update the state to be like this:
{ loggedIn: true, thisUser: { //other properties , activated: 1, } }
Firstly, this is the output of what you did:
{ loggedIn: true, thisUser: { //other properties , activated: 0, }, activated: 1, };
Secondly, JavaScript doesn’t accept this thisUser.activated
as a key.
The solution:
{ ...state, thisUser: { ...state.thisUser, activated: action.payload }, };