1

i'm fetching data from my backend api and setting the data to my state but it's returning an empty array and idk why this happening even though in other components it works just fine

this is my code :

import { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import Loader from "../ui/svg/Loader/Loader";
import classes from "./CartDetails.module.scss";

const CartDetails = () => {
  const name = useParams().name;
  const id= useParams().id;
  const [pending, setPending] = useState(true);
  const [products, setProducts] = useState([]);

  useEffect(() => {
    async function fetchItems() {
      const data = await fetch(`http://localhost:8000/api/cart/${id}`);
      const res = await data.json();
      setProducts(res); 
      setPending(false);
    }

    fetchItems();
  }, []);

  return ( 
    <>
      {pending && <Loader/>}
      <div>
        <h1>{name}'s Cart</h1>
        {products.map(product => {
          <div key={product.name}>
            <h1>{product.name}</h1>
            <img src={product.image} alt={product.name} />
          </div>
        })}
      </div>
    </>
  );
}

export default CartDetails;
5
  • is res an empty array? if thats the case, the problem does not appear to be with the react code but rather server code. Commented Aug 25, 2021 at 0:58
  • 2
    When your API is returning an empty array, maybe it's a good idea to look into the backend? When you inspect the request and response in your browser's network debugger, how does it look like? Is the ID properly filled? Does the backend return an array? Are there any JavaScript errors on the console? Note that you should have id as a dependent field in your useEffect array. Commented Aug 25, 2021 at 0:58
  • Another important thing to note. Writing async code like this inside useEffect may cause memory leaks Commented Aug 25, 2021 at 1:02
  • @digitalbreed No errors in console and when i log the res array it shows the wanted array, the problem is with setting the res to the state Commented Aug 25, 2021 at 14:10
  • @HazemBenAbdelhafidh I am afraid I am not seeing any issues in the given code. Commented Aug 25, 2021 at 18:33

2 Answers 2

1

I was just missing a return in the .map function

Sign up to request clarification or add additional context in comments.

Comments

0

Go through following for better coding . no need to use useParams() two times and while rendering data it is better to split code which makes coding better to debug

    const CartDetails = () => {
  
  const { name, id } = useParams();
  
  const [pending, setPending] = useState(true);
  const [products, setProducts] = useState([]);

  useEffect(async () => {
    
      const data = await fetch(`http://localhost:8000/api/cart/${id}`);
      const res = await data.json();
      setProducts(res); 
      setPending(false);
   
  }, []);

  const showProduct = (product) => {
      return ( 
                <div key={product.name}>
                    <h1>{product.name}</h1>
                    <img src={product.image} alt={product.name} />
                </div>
             )
  }

  const showCartDetails = () => {
       return (
            <div>
               <h1>{name}'s Cart</h1>
               {
                  products.map(product => showProduct(product)
              )}
            </div>
       )
  }

  return ( 
    <>
      {pending ? <Loader/> : showCartDetails()}
   
    </>
  );
}

export default CartDetails;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.