skip to Main Content

I am fetching an API and setting response data in the products array. But, the products array state is not updating and returning an empty array.
here is my code,

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

    useEffect(() => {
        const apiCaller = async () => {
            const res = await axios.get('http://127.0.0.1:2000/');
            const pro = await res.data;
            setProducts(pro);
            console.log(products);
         }
        apiCaller();
    }, []);

I have tried passing the ‘products ‘ in the dependency array but that results in infinite renders.

2

Answers


  1. You are getting an empty product array as the state gets updated after the useEffect is unmounted.

    So instead of printing product inside useEffect try to write outside it.

         const [products, setProducts] = useState([]);
    
    
         useEffect(() => {
                const apiCaller = async () => {
                    const res = await axios.get('http://127.0.0.1:2000/');
                    const pro = await res.data;
                    setProducts(pro);
                 }
                apiCaller();
            }, []);
          console.log(products);
    

    If you want to map it after the data you receive you can do it like below inside useEffect:

    const res = await axios.get('http://127.0.0.1:2000/');
    
        const pro = await res.data;
        pro.map((product,index)=>{
           //// do the action here
        })
    
    Login or Signup to reply.
  2. the reason you can not see the value because the firrst log in inside the async funtion is getting the previous state of products is [] and setProduct is also an async and its updates will not be reflected immediately inside the same render cycle you will see the updated product out side the useEffect

    const [products, setProducts] = useState([]);
    
    useEffect(() => {
        const apiCaller = async () => {
            const res = await axios.get('http://127.0.0.1:2000/');
            const pro = res.data;
            setProducts(pro);
        };
        apiCaller();
    }, []);
    
    // This will log the updated value of products whenever it changes
    useEffect(() => {
        console.log(products);
    }, [products]);
    
    // You can do this also 
    console.log(products);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search