react native cant get data from function

Viewed 28

i want to get the product stock and use it on detail but i have a problem

i have a fucntion like this.

async function getStock(productId, erp_code) {
    let itemsStock;
    await fetch(`${GET_STOCK}${productId}`, requestOptions)
      .then(response => response.json())
      .then(result => itemsStock = result[erp_code][0].LotQTY)
      .catch(error => console.log('error', error));
    console.log(itemsStock);   i cant console.log the data 
    return itemsStock;
  }

but in return i get a promise but that's not what i want.

i mean i get the data i need in function but i cant use it out of function

thats kinda annoying

PromiseĀ {_U: 0, _V: 0, _W: null, _X: null}

how can i fix this?

1 Answers

Assuming that you are getting the response in the expected format, you need to return the value instead of assigning it.

async function getStock(productId, erp_code) {
    const itemsStock = await fetch(`${GET_STOCK}${productId}`, requestOptions)
      .then(response => response.json())
      .then(result => result[erp_code][0].LotQTY)
      .catch(error => console.log('error', error));
    console.log(itemsStock);
    return itemsStock;
  }

Also, you can just use the async-await approach instead of .then and .catch chain:

async function getStock(productId, erp_code) {
    try {
        const response = await fetch(`${GET_STOCK}${productId}`, requestOptions);
        const result = await response.json();
        const itemsStock = result[erp_code][0].LotQTY;
        console.log(itemsStock);
        return itemsStock;
    } catch (error) {
        console.log({ error });
    }
}
Related