How to update the useState in the promise function of the react js

Viewed 211

As I want to update the products array loaded from the API in the useState but as I update it shows me the error in the console but it works I want to solve that error

const [loading, setloading] = useState(true);
const [productslist, setproductslist] = useState([]);
const currentSlug = useParams();
const BrandWiseProduct = () => {
    setloading(true);
    api.get(`brand/${currentSlug.slug}/`).then((response) => {
        setproductslist(response.data);
    });
    setloading(false);
};

const ProductCardRender = productslist.map((product, index) => {
    return (
        <ProductCard
            name={product.name}
            price={product.price}
            key={product.id}
            slug={product.slug}
            image={product.card_banner}
        />
    );
});

This is the code and here is the screenshot of the error enter image description here enter image description here

If there is any better way then please suggest to me you can share any article or blog post.

Thanks in Advance

1 Answers

Actually, might be able to do it like this:

import { useEffect, Suspense } from "react";

const ProductCardRender = () => {
  const [loading, setloading] = useState(true);
  const [productslist, setproductslist] = useState([]);
  const currentSlug = useParams();

  useEffect(() => {
    const BrandWiseProduct = () => {
      setloading(true);
      api.get(`brand/${currentSlug.slug}/`).then((response) => {
        setproductslist(response.data);
      });
      setloading(false);
    };
    BrandWiseProduct();
  }, []);
  return (
    <Suspense fallback={<h1>Loading...</h1>}>
      {productslist.map((product, index) => (
        <ProductCard
          name={product.name}
          price={product.price}
          key={product.id}
          slug={product.slug}
          image={product.card_banner}
        />
      ))}
    </Suspense>
  );
};
Related