Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

fetch request returning promise

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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();
  }, [])

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading