How to store API response in state variable and use later in React

Viewed 19

I'm trying to display the result i got from APi call on my page the result is an object i try to save the result in a state variable then later use it but i got error when i try to access it. bellow is my code

const Home = () => {
   const [products, setProducts] = useState({});

useEffect(() => {
    storeProducts();
  }, [])

      const storeProducts = async () => {
        const url = "https://api.oneb.cn/1688/item_search/?q=男鞋&start_price=0&end_price=0&page=1&cat=0&discount_only=&sort=&page_size=40";
         try{
            const response = await fetch (url);
            const data = await response.json();
            setProducts(data);
         }catch(err){
            console.log(err);
         }
      }
    
    console.log(Array(products.items));
    
    }

if I console.log(products) i get the data below

"items": {
        "page": "1",
        "real_total_results": 1900,
        "total_results": 1900,
        "page_size": 19,
        "pagecount": 100,
        "item": [
               
            {
                "title": "2022 Forrest Gump Men's Shoes Sneakers",
                "pic_url": "https://cbu01.alicdn.com/img/ibank/O1CN0169mRVd28cyyzgQQot_!!2735587954-0-cib.jpg",
                "promotion_price": "23.50",
                "price": "23.50",
                "sales": 9767,
                "turnover": "3万+",
                "num_iid": "643775889196",
                "seller_nick": "望都县普乐达商贸有限公司",
                "tag_percent": "19%",
                "area": "望都县",
                "detail_url": "https://detail.1688.com/offer/643775889196.html"
            },
            {
                "title": "2022 Martin Men's Shoes Pigskin Autumn",
                "pic_url": "https://cbu01.alicdn.com/img/ibank/O1CN01iURzli2Ka1udcUHnM_!!2212881679572-0-cib.jpg",
                "promotion_price": "83.00",
                "price": "83.00",
                "sales": 223,
                "turnover": "1万+",
                "num_iid": "680418137900",
                "seller_nick": "惠安榀尚上品鞋厂",
                "tag_percent": "20%",
                "area": "惠安县",
                "detail_url": "https://detail.1688.com/offer/680418137900.html"
            },
           
           
        ],
    }

now i try to display the product and i do like below

This is not working using state variable
<div className="row hotDealProduct">
        {Array(products.items).map((values) => {
            return (
              <div className="col-lg-3 col-md-4 col-sm-6 col-6">
                <span>Total: {values.total_results}</span>
                {values.item.map((val) => (
                  <>
                    <div className="productImage">
                      <img
                        style={{ height: "100%", width: "100%" }}
                        src={val.pic_url}
                        alt=""
                      />
                    </div>
                    <Link
                      to="/"
                      style={{ textDecoration: "none", color: "#1a1a1a" }}
                    >
                    <div className="cardDetail">
                      <div>
                        <p>{val.title}</p>
                      </div>
                      <div>
                        <h6>¥ {val.price}</h6>
                      </div>
                      <div>
                        <h6>{val.sales}</h6>
                      </div>
                    </div>
                    </Link>
                  </>
                ))}
              </div>
            );
        })}
      </div>

but i get error TypeError: Cannot read properties of undefined (reading 'total_results') andi try to remove this line and i also get error Cannot read properties of undefined (reading 'item')

If I didn't use the state variable and do something like below then it works but since am using API i need to be able to process the data dynamically

const prod = "items": {
            "page": "1",
            "real_total_results": 1900,
            "total_results": 1900,
            "page_size": 19,
            "pagecount": 100,
            "item": [
                   
                {
                    "title": "2022 Forrest Gump Men's Shoes Sneakers",
                    "pic_url": "https://cbu01.alicdn.com/img/ibank/O1CN0169mRVd28cyyzgQQot_!!2735587954-0-cib.jpg",
                    "promotion_price": "23.50",
                    "price": "23.50",
                    "sales": 9767,
                    "turnover": "3万+",
                    "num_iid": "643775889196",
                    "seller_nick": "望都县普乐达商贸有限公司",
                    "tag_percent": "19%",
                    "area": "望都县",
                    "detail_url": "https://detail.1688.com/offer/643775889196.html"
                },
                {
                    "title": "2022 Martin Men's Shoes Pigskin Autumn",
                    "pic_url": "https://cbu01.alicdn.com/img/ibank/O1CN01iURzli2Ka1udcUHnM_!!2212881679572-0-cib.jpg",
                    "promotion_price": "83.00",
                    "price": "83.00",
                    "sales": 223,
                    "turnover": "1万+",
                    "num_iid": "680418137900",
                    "seller_nick": "惠安榀尚上品鞋厂",
                    "tag_percent": "20%",
                    "area": "惠安县",
                    "detail_url": "https://detail.1688.com/offer/680418137900.html"
                },
               
               
            ],
        }

and use like this....

This is working using local variable
<div className="row hotDealProduct">
            {Array(prod.items).map((values) => {
                return (
                  <div className="col-lg-3 col-md-4 col-sm-6 col-6">
                    <span>Total: {values.total_results}</span>
                    {values.item.map((val) => (
                      <>
                        <div className="productImage">
                          <img
                            style={{ height: "100%", width: "100%" }}
                            src={val.pic_url}
                            alt=""
                          />
                        </div>
                        <Link
                          to="/"
                          style={{ textDecoration: "none", color: "#1a1a1a" }}
                        >
                        <div className="cardDetail">
                          <div>
                            <p>{val.title}</p>
                          </div>
                          <div>
                            <h6>¥ {val.price}</h6>
                          </div>
                          <div>
                            <h6>{val.sales}</h6>
                          </div>
                        </div>
                        </Link>
                      </>
                    ))}
                  </div>
                );
            })}
          </div>

so state variable to working but local variable working what am i doing wrong here

2 Answers

It's returning undefined because map() method work only on array and you are trying to use on object.

You can directly use your state like this:

products?.items?.item?.map();

No need to use.

Array(products.item)

the obj from API is

"items": {
        "page": "1",
        "real_total_results": 1900,
        "total_results": 1900,
        "page_size": 19,
        "pagecount": 100,
        "item": [
               
            {
                "title": "2022 Forrest Gump Men's Shoes Sneakers",
                "pic_ur

It will be

products?.items?.item?.map((values) =>

Hope that helps,

Mauro

Related