Home > database >  Redux object Object is not extensible error when creating new attribute for array of objects
Redux object Object is not extensible error when creating new attribute for array of objects

Time:11-17

i need to delete a property to an object or delete based on the user action- if the selected property is already added , i need to remove this proporty if its not added i have to remove this

const { customAllAreas } = useSelector((state) => state.AreasReducer);
  const saveArea = (area) => {
    const newFilteredAreas = customAllAreas?.map((f) => {
      if (f?._id === area?._id) {
        if (f.selected) {
          delete f.selected;
        } else {
          f.selected = true;
        }
        return f;
      }
      return f;
    });
    dispatch(AreasAction.setcustomeAddedAreas(newFilteredAreas));
  };

CodePudding user response:

You are mutating the customAllAreas that is stored in redux.

delete f.selected; // mutation

f.selected = true; // mutation

You should make a copy of customAllAreas before doing so.

const newFilteredAreas = [...customAllAreas].map((...))

Or try the immutable way:

const newFilteredAreas = customAllAreas?.map((f) => {
  if (f?._id === area?._id) {
    if (f.selected) {
      const { selected, ...rest } = f;
      return rest;
    } else {
      return { ...f, selected: true };
    }
  }

  return f;
});
  • Related