user8934737
user8934737

Reputation:

how to update redux state using immutability helper?

I am trying to update my redux crud form.I am using with the help of immutatbility helper. My reducer is:

case UPDATE_TODO:
console.log("reducer todo",action.toDo,state)
return update(state, { $set: [action.toDo] })

But instead of replacing specific object it replace whole array into one.Where I am doing wrong?? My State is this:

[
{_id: "5b3d2696e099830f249dddfd", title: "hello", description: "hello", reminder: "2018-07-05T01:27", date: "1530734230965", …}
{_id: "5b3d2696e099830f249dddxe", title: "hello", description: "hello", reminder: "2018-07-05T01:27", date: "1530734230965", …}
]

and after updating it should be like this:

[
{_id: "5b3d2696e099830f249dddfd", title: "hello", description: "hello", reminder: "2018-07-05T01:27", date: "1530734230965", …}
{_id: "5b3d2696e099830f249dddxe", title: "hello1", description: "hello", reminder: "2018-07-05T01:27", date: "1530734230965", …}
]

but instead its giving result this:

[
{_id: "5b3d2696e099830f249dddxe", title: "hello1", description: "hello", reminder: "2018-07-05T01:27", date: "1530734230965", …}
]

Upvotes: 0

Views: 506

Answers (1)

humanshado
humanshado

Reputation: 188

Your code is not targeting the specific todo you want to update in state, hence it replaces the whole state. There are two ways you can achieve this:

1) Find the index of the todo item you want to update using Array.findIndex method before using $set method.

const todoIndex = state.findIndex(todo => todo.id === action.toDo.id)
const newState = update(state, {[todoIndex]: {$set: action.todDo }})

2) Find the index of the todo item you want as (1) above and then use $splice method.

const todoIndex = state.findIndex(todo => todo.id === action.toDo.id)
const newState = update(state, {$splice: [[todoIndex,1,action.todDo]]})

Upvotes: 1

Related Questions