skip to Main Content

Data is being duplicated when item is inserted into React js Array state,

console.log(newData)

outputs a single object, while

console.log(data)

outputs continuous duplicate of

console.log(newData)

How do i fix it

 const [data, setData] = useState([])

    const addData = (newData) => {
       
        console.log(newData)
        setData(prevData => [...prevData, newData]);
        console.log(data)
        
    };

    useEffect(() => {
          axios
            .get(`http://localhost:3000/api/products/${pid}`)
            .then((res) => {
              addData(res.data); // Update the state directly with the response data
            })
            .catch((err) => {
              console.log(err);
            });
       
    });

2

Answers


  1.     useEffect(()=> {
       axios
                .get(`http://localhost:3000/api/products/${pid}`)
                .then((res) => {
                  addData(res.data); // Update the state directly with the response data
                })
                .catch((err) => {
                  console.log(err);
                });
    }, [data]) // Add the [data] (The dependency array) to say that we want this renders only when this var changes
    
    Login or Signup to reply.
  2.  const [data, setData] = useState([])
        const addData = (newData) => {
            console.log(newData)
            setData(prevData => [...prevData, newData]);
            console.log(data)
        };
    
        useEffect(() => {
          // even if useEffect is called again, you will only execute code, if your state array is empty
          if(data.length === 0){
            axios
            .get(`http://localhost:3000/api/products/${pid}`)
            .then((res) => {
               cosole.log("res.data", res.data);
              // make sure res.data is an array
              addData(res.data); // Update the state directly with the response data
            })
            .catch((err) => {
              // always use console.error() to print the errors
              console.error(err);
            });
          }
        }, []); 
    //  add your dependency here, I kept it empty, 
    // because I assume, you want to add the data in the first render only
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search