Search code examples
javascriptreactjsuse-effectuse-state

Can't map fetched data on first render in React


I have an API that returns me 4 objects and I try to save them in a new array called "products" and map them to the DOM. My problem is that map function doesn't work on first render.

If I modify something in my code, save the file and watch the react page again, I will see that my data appeared.

How can I fix that?

import { useEffect, useState } from 'react';
import './App.css';

function App() {

  const [products, setProducts] = useState([]);

  useEffect(() => {
    fetch("URL")
    .then(res => res.json())
    .then(data => {
      for(let i = 0; i < data.length; i++) {
        products.push(data[i])
      }
    })
  })

  console.log(products);

  return (
    <div className="App">
      {products.map((product,index) => (
        <div key={index}>{product.price}</div>
      ))}
    </div>
  );
}

export default App;


Solution

  • const [products, setProducts] = useState([]);
    
    useEffect(() => {
        async function getdata() {      
          const res = await fetch("URL");
          const data = await res.json();
          setProducts(data)
        }
    
        let unmounted = false;    
        if (!unmounted) {
          getdata();
        }
    
        return () => unmounted = true;
    }, []);
    

    You can try this, I hope It will be work.