0

let's say I've data stored in a redux state like this

state = {
records : [
    {id:"1", name:"foo", city:"A"},
    {id:"2", name:"bar", city:"B"},
    {id:"3", name:"abc", city:"C"},
]
}

how do I change any attribute of any record dynamically using immutable way?

0

2 Answers 2

1

Something like this:

case 'SOMETHING': 
const recordsCopy = {...state.records};
//change recordsCopy ...
const recordToChange = recordsCopy.find(x => x.id === '3')
if(recordToChange) {
   recordToChange.name = 'new name';
}
return {...state, records: [...recordsCopy]}
Sign up to request clarification or add additional context in comments.

8 Comments

how do I change the name of record no.3 only?
I update the answer.
if there's no id attribute it is possible to change?
Find logic is up to you and your design. You should find your item first anyway.
i mean how do i do the same thing with array index instead of id attribute
|
1

let say, you have the id (let 2) of record and you want to update name (to "pqr")

function reducer (state, action){
  const {type, payload}  = action
  switch(type){
  case: "UPDATE": 
       return updateRecord(state, payload.id, payload.newname)
  default: return state;
  }
}

function updateRecord(state, id, newName){
  const newRecords = state.records.map(rec => {
     if(rec.id === id){ return {...rec, name: newname} }
     return rec
   })
  return {...state, records: newRecords}

}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.