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?

Necrofantaisie
  • 364
  • 1
  • 4
  • 19

2 Answers2

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]}
Ehsan
  • 1,093
  • 1
  • 12
  • 21
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}

}
Harish
  • 1,841
  • 1
  • 13
  • 26