alfonsodev
alfonsodev

Reputation: 2754

react-native async fetch, undefined error

When calling GetByUsername, the execution jumps to catch block but err is undefined. The api is working because the equivalent promise style code .then().then().done() works, but I'd like to write in this async / await style better. How can I debug it ?

var cli = {
    GetByUsername: async function(username) {
       try {
         let resposne = await fetch(`http://api.example.com?username=${username}`);
         return response;
       } catch(err) {
         debugger;
       }
    }
}

edit: By looking at react-native's package.json it seems that the fetch implementation used is node-fetch and babeljs as transpiler.

Upvotes: 0

Views: 2869

Answers (2)

lxl
lxl

Reputation: 21

try this:

const response = await fetch(`http://api.example.com?username=${username}`);
const jsonData = await response.json();
// then you can use jsonData as you want

Upvotes: 2

alfonsodev
alfonsodev

Reputation: 2754

I found the problem was a misspelled variable, so I was returning a non existing variable, that cause the execution to end in the catch block with an undefined Error.

Upvotes: 0

Related Questions