Home > database >  React Parent/Child Components sync data when the data is unrelated
React Parent/Child Components sync data when the data is unrelated

Time:08-28

I'm having a problem with unrelated arrays that seem to take the same value.. Here is my code sample and the description of the problem if anyone can help please https://codesandbox.io/s/aged-frost-thwsfz?file=/src/App.js

My problem:

  • 2 components. 1 listing exercises and opening in a mui modal another component
  • I make updates in the modal (edit the text field, delete an entry from the table)
  • If I close the modal (click outside the modal) the modal closes and the values filled in text boxes are reflected in the parent component
  • Sorting and deleting do update the table in the child modal component, but if i close, sorting and deleting are not reflected in the parent component (which is something I expect and want).. If I click X or close component without clicking on save, I'm actually canceling my updates.
  • Why do value propagate to parent component

In real life:

  • I have a react-hook-form and the modal is to edit the values.
  • I even have SortableJs in place that I can sort my list
  • The code is a bit messy since I was trying things like spread operator on the array and even lodash clone to make sure that parent and child have different copies of the array but no, the field still updates!

CodePudding user response:

_. clone() function creates a shallow copy of the given object. The nested objects or arrays will be copied using reference, not duplicated.

In your handleExercisetimeUpdate function, you are directly updating the referencing value with the new value..

 const handleExerciseTimeValueUpdate = (itemId, value) => {
    let copy = _.clone(editExercisesList);
    // let entry = copy.find((e) => e.id === itemId);
    // entry.time = value; -> which directly updates the reference.
    // Instead
    let entry = copy.map((e) => (e.id === itemId ? { ...e, time: value } : e));
    setEditExercisesList(entry);
  };

  • Related