0

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},
           ]
5

2 Answers 2

1

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};
        }
      }
    )
  }
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.