Eliran Nider
Eliran Nider

Reputation: 75

React get returned value from function with fetch

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
    }

Upvotes: 0

Views: 33

Answers (1)

tar
tar

Reputation: 1568

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
}

Upvotes: 1

Related Questions