1

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));
  };

1 Answer 1

1

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

4 Comments

tried but not working--const newFilteredAreas = [...customAllAreas]?.map((f) => { if (f?._id === area?._id) { if (f.selected) { delete f.selected; } else { f.selected = true; } return f; } return f; });
@Andaman Try to remove both of the lines I posted above. Just to check if the error will be gone
Kind user- If i remove both lines ,then how can i add and delete selected property
@Andaman Just try the immutable way instead of direct mutation as e.g. delete f :) Check my updated answer.

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.