Home > Back-end >  All states are empty after running setState
All states are empty after running setState

Time:07-16

As a beginner, I am having trouble with doing a simple API request and looping back the state. The API route returns the data requested which has been tested, so I think backend is not the trouble. The real tricky error surely has to do with react I think. I setup a several states and using the useEffect which calls a function where the data will be requested using axios. The data returns and setStae actually works. When also checking the values of the states from browser react extension, it also shows that the data is already in the state. And if the state was console logged and checked through console on browser. It shows that it has data.

But here is when it becomes funny. Even though, doing console logged inside the function where axios request the data and run setState works, when doing console logged outside of the function, it shows that none of the states have data. But still the browser extension tool shows that there is data inside the state.

And also looping the state does not work at all since it clearly has no data. It is really getting weird. Because the browser shows that there is data in the states but when actually looping it or running console log, it does not show anything at all.

import axios from "axios";
import React, { Fragment, useEffect, useState } from "react";
import Spinner from "../Component/Spinner";

export default function Home() {
    const [category, setCategory] = useState([]);
    const [productByCategory, setProductByCategory] = useState([]);
    const [loader, setLoader] = useState(true);
    const [featureProduct, setFeatureProduct] = useState([]);

    const fetchProduct = () => {
        axios.get("/api/home").then((d) => {
            const { category, featureProduct, productByCategory } = d.data.data;
            setCategory(category);
            setFeatureProduct(featureProduct);
            setProductByCategory(productByCategory);
            setLoader(false);
        });
    };

    useEffect(() => {
        fetchProduct();
    }, []);
    
    return (
        <Fragment>
            {loader && <Spinner />}
            {!loader && (
                <Fragment>
                    <div className="w-80 mt-5">
                        <div className="row mt-2">
                            {/* loop category */}
                            {category.map((c) => {
                                <div
                                    className="col-12 col-sm-12 col-md-3 col-lg-3 border"
                                    key={c.slug}
                                >
                                    <a href="" className="text-dark">
                                        <div className="d-flex justify-content-around align-items-center p-3">
                            

                                        <img
                                            src={c.image}
                                            width={100}
                                            alt=""
                                        />
                                        <div className="text-center">
                                            <p className="fs-2">{c.name}</p>
                                            <small className="">
                                                {c.product_count}
                                            </small>
                                        </div>
                                    </div>
                                </a>
                            </div>;
                        })}
                    </div>
                </div>

CodePudding user response:

You're not returning anything from your map . Also a console.log won't show data as setState is asynchronous so the log runs before the state is set. Read more here Why is setState in reactjs Async instead of Sync?

  category.map((c) => {
//return missing
return <div className="col-12 col-sm-12 col-md-3 col-lg-3 border" key={c.slug}>
      <a href="" className="text-dark">
        <div className="d-flex justify-content-around align-items-center p-3">
          <img src={c.image} width={100} alt="" />
          <div className="text-center">
            <p className="fs-2">{c.name}</p>
            <small className="">{c.product_count}</small>
          </div>
        </div>
      </a>
    </div>;
  })
  • Related