0

I am having trouble returning the response for a API call in my React Native project.

let response = fetch('http://3.133.123.120:8000/auth/token', {
    method: "POST",
    headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({
        client_id: 'NTMtzF7gzZPU9Ka35UFsDHvpR8e4D1Fy4OPRsurx',
        grant_type: 'password', 
        username: user, 
        password: pass, 
    })
})
.then((response) => response.json())
.then((response) => this.setState({jsonData: response}))
.then(() => alert('resposne jsonData: ' + JSON.stringify(this.state)));
alert('resposne jsonData: ' + JSON.stringify(response))

The code above returns the correct response in the bottom .then() statement, however, I have not been able to use the data outside of the fetch() statement.

Anything I've tried to use outside of the fetch() (like my alert in bottom line) has given me the following...

{"_40":0,"_65":0,_55":null,"_72":null}

Please also note this is all inside a React class Component

John Salzman
  • 500
  • 5
  • 14
  • 1
    If you want to use the respond outside fetch function, you should set the response as an async function, or use Promise. – Kuo-hsuan Hsu Mar 27 '20 at 01:02
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – ggorlen Mar 27 '20 at 01:10

1 Answers1

1

fetch returns a Promise: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

You already have access to the value in that final then. If you're looking for a way to use the value below without using a callback, you could consider async/await style and wrapping this code in a function like so:

const fetchData = async () => {
  const results = await fetch() // put your fetch here
  alert(results.json());
};

fetch info: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

async/await info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

sdotson
  • 790
  • 3
  • 13
  • I have tried this but when I return the results, it gives me {"_40":0,"_65":0,_55":null,"_72":null} while in the actual function, it gives me the correct output – John Salzman Mar 27 '20 at 01:37
  • does it work if you remove those final 2 `then` statements?: `.then((response) => this.setState({jsonData: response}))` and `.then(() => alert('resposne jsonData: ' + JSON.stringify(this.state)));` – sdotson Mar 27 '20 at 01:53
  • It works as in it returns data.However, I cannot get any of the data out of the function – John Salzman Mar 27 '20 at 01:57
  • 1
    @JohnS I've updated the answer so that it is more specific to `fetch`, would would require doing `response.json()` to actually get the json from the response. My original answer applies more to promises in general. You can read more here. – sdotson Oct 01 '20 at 19:01