fedormoore
fedormoore

Reputation: 15

Child changes the value in parent

I pass an array from the parent, in the child I receive it through a props and pass it to the state. After that, I need to add a field to the array, I do this in useEffect. But as soon as this goes through, the data also changes in the parent. Why is this happening?

Parent:

<IncomeDrawer values={selectRowData}/>

Child:

const [values, setValues] = useState(props.values);

useEffect(() => {
  let newData = values.docSubs;

  function updateTreeTable(data) {
    for (let i = 0; i < data.length; i++) {
      data[i] = { ...data[i], recordIndex: recordIndex };
      recordIndex++;
      if (data[i].hasOwnProperty('children')) {
        updateTreeTable(data[i].children);
      }
    }

  };
  updateTreeTable(newData);

  setValues({ ...values, docSubs: newData })

}, [])

Upvotes: 0

Views: 599

Answers (2)

Stan
Stan

Reputation: 87

I think the solution might be to use the spread operator like that:

const [values, setValues] = useState([...props.values]);

As pointed out by Khabir the problem is in the props reference.

P.S. Sorry, I didn't comment, but I don't have the necessary reputation.

Upvotes: 2

Khabir
Khabir

Reputation: 5844

When you pass props into your child component, it passes the reference. so if you change the value in child component which came from parent, it will change in both child and parent.

To avoid this, you need to clone your props value into your child component before changing it.

In React, actually in JavaScript, there are many ways to clone object/array

Using slice function

const [values, setValues] = useState(props.values.slice());

Using Spread Operator

const [values, setValues] = useState([...props.values]);

Using JSON.parse and JSON.stringify function

const [values, setValues] = useState(JSON.parse(JSON.stringify(props.values));

There are some other ways to clone your array. you google it if you want to know.

Upvotes: 3

Related Questions