skip to Main Content

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


  1. 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:

    const DefaultTabGroup = ({data}) => {
    
    const [transformedData, setTransformedData] = useState([]);
    
    useEffect(() => { setTransformedData( data.map((d) => { return { ...d, connectors: [] } }) ); }, [data]);
    
    //code.....
    
    }
    

    Hope this helps!

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search