1

The following is my component where the props data getting updated when the searchItem() has been executed. I can't understand why this is happening. How can I fix this issue?

const DefaultTabGroup = ({data}) => {

const [res , setRes] = useState({});

useEffect(() =>{
   setRes(data);
},[data]);


const searchItem = () =>{
    let transData = [];
    res.map((d) =>{
       let a = d;
       a.connectors = [];
       transData.push(a);
    });
};

//code.....

}
export default DefaultTabGroup;
SubrataG
  • 137
  • 1
  • 12
  • because data is a reference So when you make setRes(data), res === data, they are the same reference. If you want to avoid that, you can make the following : setRes({...data}) – Dimitri Bosteels May 24 '23 at 13:13

1 Answers1

0

You should not change/mutate the state directly in React (Here is an answer in stackoverflow about that).

import React, { useState, useEffect } from 'react';

const DefaultTabGroup = ({ data }) => {
  const [res, setRes] = useState([]);

  useEffect(() => {
    setRes(data);
  }, [data]);

  const searchItem = () => {
    const transData = res.map((d) => {
      const a = { ...d }; // Create a copy of the object
      a.connectors = []; // Modify the copied object
      return a;
    });

    // code ...
    setRes(transData);
  };
};

export default DefaultTabGroup;

You should create a new array "transData" and update the state with that.

Pishameni
  • 485
  • 5
  • 10