Search code examples
javascriptreactjsreact-reduxreact-state-management

Update a value in the object in an Array in react in Redux


I am dispatching an action that will update the values in the redux state and I am passing an array. But before that, I want to update the array by changing the object values but I keep getting an error - Cannot assign to read only property 'position' of object

I am not sure why I am getting this error because I am creating a new Array and updating the values in that.

Code

export const GetCustomers= (customers) => (dispatch, getState) => {
  let activeCustomers = Array.from(customers);
  for (let i = 0; i < activeCustomers.length; i += 1) {
     activeCustomers[i].position = i;
  }

  dispatch(actions.updateActiveCustomers(activeCustomers));
  );
};

Getting an error - Cannot assign to read only property 'position' of object

I am not sure why I am getting this error because I am creating a new Array and updating the values in that.


Solution

  • To deep copy use:

      let activeCustomers = JSON.parse(JSON.stringify(customers));