'How to change just one parameter using Redux?
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?
Solution 1:[1]
Well, your syntax is wrong, that's what. :)
case 'users/setActivated':
return { ...state, thisUser: {...state.thisUser, activated: action.payload} }
is what you need to shallow-merge state with a shallow-merged nested object.
Note that it quickly gets very old to dig into objects like that, and you might want to look at e.g. immer.
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 | AKX |
