Answer the question
In order to leave comments, you need to log in
How can I immutably return a new object (state) in Redux?
Good afternoon!
Understanding Redux. Tell me, please, how can I immutably return an object in this and similar cases! The point is that when designing an application, a state object arises with a certain level of nesting. It's still not clear to me how boolean properties can be changed inside nested objects! When I do, as in the code below (action 'TOGGLE_COMPLETED' ) in React, an error occurs due to the fact that map () does not have time to return a new modified array.
//reducer.js
const initState = {
todo: []
}
export default function reducer (state = initState, action) {
switch(action.type){
case 'ADD_TODO':
return Object.assign({}, state, {
todo: [
...state.todo,
{
id: action.id,
text: action.text,
completed: false
}
]
})
case 'TOGGLE_COMPLETED':
return Object.assign({}, state, {
todo: state.todo.map((item) => {
if(item.id == action.id) {
item.completed = !item.completed
}
})
})
default:
return state
}
}
Answer the question
In order to leave comments, you need to log in
Forgot to add:
case 'TOGGLE_COMPLETED':
return Object.assign({}, state, {
todo: state.todo.map((item) => {
if(item.id == action.id) {
item.completed = !item.completed
}
return item;
})
})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question