Ryan94
Ryan94

Reputation: 331

React Native possible unhandled Promise rejection

I'm trying to get values from an API using fetch function of React Native. Then label values retrieved from JSON as Millions , Billions ... etc.

JSON File

{
  "value": 92060,
  "new": 1
} 

To Do what I wanted, I used below code.

async componentDidMount() {

let data =  await fetch('https://demo614535421.mockable.io/getData')
.then((response) => response.json())
.then((responseJson) => {
  this.setState({
    grossRev : this.getCodedValues(responseJson.grossRevenue)
  })

})
.catch((error) => {
  console.error(error);
});
this.setState({ wowData: true });
return data;

}

And getCodedValues() function,

getCodedValues(value)
{
  console.log(Math.abs(Number(value)));
}

Before I check millions and billions, iOS simulator started to show an error saying,

Undefined is not an Object (evaluating '_reactNative.Math.abs')

I used async and await here to hold functions while data are being captured. But still seems like in getCodedValues function value parameter is undefined?

Problem

  1. How can I solve this and do the arithmetic calculations?

Upvotes: 0

Views: 8736

Answers (1)

Sujil Maharjan
Sujil Maharjan

Reputation: 1377

How about this? This only uses async/await and doesn't deal with then/catch because when you use await, it waits for fetch to come back with the response.

async componentDidMount() {
   try {
      let response =  await fetch('https://demo614535421.mockable.io/getData');
      let responseJson = response.json();
      this.setState({
         grossRev: this.getCodedValues(responseJson.grossRevenue)
      })
   }catch(err){
      console.log(err);
   }
}

Upvotes: 1

Related Questions