Search code examples
javascriptrequestfetch

How to return a response from a fetch in javascript


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


Solution

  • 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