1

i created a function named getCartItems which calls getSingleItems passing id as argument. if i log the json result in getSingleItem it is showing object of the product correctly but when i try to access the function call value i get a promise how to resolve it?

const getSingleItem = async (id)=>{
    const response = await fetch("http://localhost:4000/products/"+id, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      },
    })
    const json = await response.json();
    return json;
  }

  const getCartItems = () => {
    let currArr = JSON.parse(localStorage.getItem('cart'));
    let newArr = currArr.map( async (el)=>await getSingleItem(el.id))
    console.log(newArr);
    setCartItems(newArr);
  }
  useEffect(()=>{
    getCartItems();
  }, [])

if try to use for loop instead of map it shows promise pending and throws connection error.

  • `Promise.all(currArr.map(({ id }) => getSingleItem(id))).then(setCartItems)`. There's no need to make the map callback `async` – Phil Oct 18 '22 at 06:18
  • FYI adding the `content-type` header to your GET request is unnecessary. There is no request content – Phil Oct 18 '22 at 06:21

1 Answers1

1

You need to resolve the promises from the map method with Promise.all and await for it before setting the cartItems state.

const getSingleItem = async (id)=>{
    const response = await fetch("http://localhost:4000/products/"+id, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      },
    })
    const json = await response.json();
    return json;
  }

  const getCartItems = async () => {
    let currArr = JSON.parse(localStorage.getItem('cart'));
    let newArr = await Promise.all(currArr.map( async (el)=>await getSingleItem(el.id)))
    console.log(newArr);
    setCartItems(newArr);
  }
  useEffect(()=>{
    getCartItems();
  }, [])

Mina
  • 14,386
  • 3
  • 13
  • 26