Harsh Srivastava
Harsh Srivastava

Reputation: 359

Updating array in redux State

how to update and element in an Array in REDUX state for

var initialState = {
   DataArray :[],
   isSelected : flase,
}

Ex:

var DataArray = [
               {place:NY ,Bool:true},
               {place:Boston ,Bool:true}
              ]

updated to

var DataArray =[
            {place:NY ,Bool:false},
            {place:Boston ,Bool:true},
           ]

Upvotes: 0

Views: 3223

Answers (2)

Sambit Prakash
Sambit Prakash

Reputation: 341

Check my below code. May b It will help you. Use this code in your reducer, where you want to update data in array.

return { ...state,
      stateArray: state.stateArray.map(data => {
        if (data.place === action.payload.data.place) {
          return action.payload.data;
        }
        else {
          return {place:data.place,count:data.count,selected:false};
        }
      }
    )
  }

Upvotes: 1

Faysal Ahmed
Faysal Ahmed

Reputation: 1542

Assuming you have object in payload you want to update and your action type is UPDATE_ARRAY

case 'UPDATE_ARRAY':
  let data = [...state.DataArray],
  index = data.findIndex(r => r.place === action.payload.place) //finding which index should get the udpate
  if(index > -1) //
  {
    data[index] = action.payload
    return {...state,DataArray: data}
    // ES5 --> return Object.assign({},state,DataArray: data)
  }
  else return state

Upvotes: 0

Related Questions