Home > Blockchain >  Data not showing on frontend in React
Data not showing on frontend in React

Time:12-31

I fetched data from api and updated the state.But data is not showing on frontend.Console.log() is working fine. <p>{item.title}</p>; Not working. What is the problem?

import { useEffect } from "react";
import { useState } from "react";


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

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

  const fetchProducts = () => {
    fetch("https://fakestoreapi.com/products?limit=5")
      .then((res) => res.json())
      .then((json) => {
        console.log(json);
        setProducts(json);
      })
      .catch((err) => {
        console.log(err);
      });
  };
  
  return (
    <div className="products-page">
      {products?.map((item) => {
       console.log(item.title);   // working
        <p>{item.title}</p>;      // Not working
      })}
    </div>
  );
};

export default ProductsPage; ```

CodePudding user response:

You either need to pass empty array when you define state ie const [products, setProducts] = useState([]); or have optional chaining where you map ie products?.map

import { useEffect, useState  } from "react";



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

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

  const fetchProducts = () => {
    fetch("https://fakestoreapi.com/products?limit=5")
      .then((res) => res.json())
      .then((json) => {
        console.log(json);
        setProducts(json);
      })
      .catch((err) => {
        console.log(err);
      });
  };
  
  return (
    <div className="products-page">
      {products?.map((item) => {
       return <p>{item.title}</p>;
      })}
    </div>
  );
};

export default ProductsPage; 
  • Related