0

I'm fetching an API, and it's work well. But in this case resp is always null. I'm wondering how to affect the result of this post request to the resp var.

var resp = null

fetch('http://a1a239a6.ngrok.io/api/login', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: "email=" + email + "&password=" + password,
  }).then((response) => response.json())
  .then((responseJson) => resp = responseJson)
  .catch((error) => console.error(error))

if (resp != null) {
  navigate('Welcome', {
    user: resp
  })
  console.log(resp)
}
Erazihel
  • 7,295
  • 6
  • 30
  • 53
Rafik
  • 395
  • 1
  • 2
  • 12

2 Answers2

0

I think it is because the instruction with your navigate function is executed before the api answers (asynchronous )

You need to move it within your then statement :)

Clement Levesque
  • 1,202
  • 4
  • 18
  • 30
0

You should use the callbacks provided if you want to bind data to a variable.

fetch('http://a1a239a6.ngrok.io/api/login', {
    method: 'POST'
}).then(function(response) {
    navigate('Welcome', { user: response})
}).catch(function(err) {
    // Error
});

So, on success, it'll automatically run your navigate function, you would probably want to verify your retrieved data there before this happens though.

On Error, you can run a modal now or perform an action you desire now.

Problem with your previous code was it would run async anyway, so even if in callback you would set resp to retrieved data, the logic would already run and check the null variable.

Adrian
  • 8,271
  • 2
  • 26
  • 43