0

With the function productTotalInventory below, how can I get the value total that I printed console.log(total) ? I'm getting empty sting.

I checked several answers, and tried to understand through that post, no success - Thanks!

    async function fetchObjectDetails(url, itemId) {
        try {
            const response = await fetch(url + itemId)
            const json = await response.json()

            return json
        } catch (e) {
        }
    }

    const productTotalInventory = (productId) => {
        fetchObjectDetails('http://127.0.0.1:8000/api/subProducts/?product_id=', productId)
            .then(result => {
                const total = result.reduce((totalInventory, item) => totalInventory + item.inventory_total, 0)
                console.log(total)
            })
        return total     <<<<<<<<<<<<<<<<< Return empty string
    }

1 Answers1

1

The problem is that the promise is asynchronous, so your return total line executes before the promise has resolved.

you can await it like so:

const productTotalInventory = async (productId) => {
    const result = await fetchObjectDetails('http://127.0.0.1:8000/api/subProducts/?product_id=', productId)
    const total = result.reduce((totalInventory, item) => totalInventory + item.inventory_total, 0)
    console.log(total)
    return total     <<<<<<<<<<<<<<<<< Return empty string
}
tar
  • 1,538
  • 1
  • 20
  • 33
  • Thank you! It seems like the right answer, I just got an error `Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.` because I'm trying to call it from inside a `.map(..{productTotalInventory(productDetails.id)}..)` - if you can help also with that, it'll be amazing – Eliran Nider Jul 21 '20 at 22:41
  • ah, yeah since `productTotalInventory()` is now async, it can't be used directly. I suggest (before you call .map) trying to define `const inventory = productTotalInventory(productDetails.id)` so you can then call `inventory.map(...)` etc. – tar Jul 22 '20 at 01:04