How to return the json response from the fetch API

喜欢而已 提交于 2019-12-05 19:42:38

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

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});
    });
  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!