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
  • 2
    (It doesn't make any sense anyway since total is local to your then function.) Commented Jul 21, 2020 at 21:20

1 Answer 1

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

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
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.

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.