sami ullah
sami ullah

Reputation: 1094

changing a child component state variable(array), Parent component array updates?

I am pass an array of dictionary to child component and in child component I assign the props to a state variable and when i updates the state of child component, it updates the same array passed as props in the parent component.

I try to update the table as i add a level (a table row)

  //parent component
    useEffect (()=>{
        console.log("add_level page  and N_table is :" , N_table)
        setreshow(<Table MAA={N_table}   />)
    },[add_level]) 

In Child component as I update row content It updates the parent array too!!

  // child component
       const arr = props.MAA;
       arr.sort((a,b)=> (a.key > b.key ? 1 : -1))   
       const [NN_table , setNN_table] = useState(arr) 
         
      const Changehandler =(e , x) =>{
          NN_table[x].dose = e.target.value      
          setNN_table({...NN_table })   
      }

Thanks for your time!!

Upvotes: 0

Views: 108

Answers (1)

Rao Virinchi
Rao Virinchi

Reputation: 329

This is happening because you passed your array as a reference. When you say MA={N_table}, a reference to the parent's table is being passed to the child component. Similarly, when you set the state using useState in the child component, you are passing the reference to the N_table(which was passed as a prop to the child component). So when you updated the table in the child component, since the stored table was a reference to the parent's table, that got updated too. To prevent this, use a spread operator when you want to pass an array by value instead of reference.

One way to fix the code is as follows:

// child component
       const arr = props.MAA;
       arr.sort((a,b)=> (a.key > b.key ? 1 : -1))   
       const [NN_table , setNN_table] = useState([...arr]) 
         
      const Changehandler =(e , x) =>{
          const dummyTable = [...NN_table];
          dummyTable[x].dose = e.target.value;
          setNN_table({dummytable });
      }

Upvotes: 0

Related Questions