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;
2
Answers
The issue here is that when the searchItem() function is executed, it is directly manipulating the res state variable that was set by the useEffect hook which updates the res variable whenever the data prop changes. This causes the component to re-render with the updated res state variable, which then triggers the useEffect hook again, setting res to the same value as data. To fix this issue, you should create a separate state variable for the transformed data and update it instead of the original res state variable. Here is an example:
Hope this helps!
You should not change/mutate the state directly in React (Here is an answer in stackoverflow about that).
You should create a new array "transData" and update the state with that.