How to return the json response from the fetch API

11,770

Solution 1

Use callback

check_auth(callback){
    fetch(Urls.check_auth(), {
      credentials: 'include',
      method: 'GET'
    }).then(response => {
      if(response.ok) return response.json();
    }).then(json => {
      callback(json.user_logged_in);
    });
  }

 check_auth(function(data) {
        //processing the data
        console.log(d);
    });

In React it should be easier to handle, You can call a fetch and update the state, since on every update of state using setState the render method is called you can use the state to render

check_auth = () =>{
    fetch(Urls.check_auth(), {
      credentials: 'include',
      method: 'GET'
    }).then(response => {
      if(response.ok) return response.json();
    }).then(json => {
         this.setState({Result: json.user_logged_in});
    });
  }

Solution 2

Async calls doesn't always resolve to be used anywhere within your app when you use .then(). The call is still async and you need to call your if-statement when you are calling your fetch. So anything that relies on the data you are fetching has to be chained to the fetch with .then().

  check_auth(){
        fetch(Urls.check_auth(), {
          credentials: 'include',
          method: 'GET'
        }).then(response => {
          if(response.ok) return response.json();
        }).then(json => {
          return json.user_logged_in;
        }).then(user => checkIfAuthSuccess(user)); //You have to chain it
      }

Wrapping your if-statement in a function or however your code looks like.

checkIfAuthSuccess(user){

  if(user){
     // do stuff
  } else {
    // do other stuff
  }
}

Nice video about async behavior in JavaScript: Philip Roberts: What the heck is the event loop anyway? | JSConf EU 2014

Solution 3

it can be solved with the es6 aync functions

Note: the example is different from what OP asked but it gives some hints on how it should be done


const loadPosts = async () => {

  const response = await fetch(/* your fetch request */);

  const posts = await response.json();

  return posts;

};

Share:
11,770
Brad Evans
Author by

Brad Evans

Updated on June 27, 2022

Comments

  • Brad Evans
    Brad Evans almost 2 years

    I have a function like so:

    check_auth(){
        fetch(Urls.check_auth(), {
          credentials: 'include',
          method: 'GET'
        }).then(response => {
          if(response.ok) return response.json();
        }).then(json => {
          return json.user_logged_in;
        });
      }
    

    And then I try to do this:

    if(this.check_auth()){
        // do stuff
    } else {
        // do other stuff
    }
    

    But, this.check_auth() is always undefined.

    What am I missing here? I thought that within fetch's then() was where the resolved Promise object was therefore I thought that I'd get true when the user was logged in. But this is not the case.

    Any help would be greatly appreciated.