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:
JavaScript
x
16
16
1
const initialState = {
2
loggedIn: false,
3
thisUser: {}
4
}
5
6
export function usersReducer(state = initialState, action) {
7
switch (action.type) {
8
case 'users/loggedIn':
9
return { state, loggedIn: action.payload }
10
case 'users/addUser':
11
return { state, thisUser: action.payload }
12
default:
13
return state
14
}
15
}
16
I tried to write a new case like, but doesn’t work:
JavaScript
1
3
1
case 'users/setActivated':
2
return { state, thisUser.activated: action.payload }
3
VS Code doesn’t let me write that “.activated”
My dispatch look like:
JavaScript
1
2
1
dispatch({ type: 'users/setActivated', payload: 1 })
2
What is wrong?
Advertisement
Answer
I understand why you did this, it seemed logical to you, but it will not work.
JavaScript
1
5
1
const state = {
2
state,
3
[thisUser.activated]: action.payload
4
};
5
So your goal is to update the state to be like this:
JavaScript
1
8
1
{
2
loggedIn: true,
3
thisUser: {
4
//other properties ,
5
activated: 1,
6
}
7
}
8
Firstly, this is the output of what you did:
JavaScript
1
9
1
{
2
loggedIn: true,
3
thisUser: {
4
//other properties ,
5
activated: 0,
6
},
7
activated: 1,
8
};
9
Secondly, JavaScript doesn’t accept this thisUser.activated
as a key.
The solution:
JavaScript
1
8
1
{
2
state,
3
thisUser: {
4
state.thisUser,
5
activated: action.payload
6
},
7
};
8