Home > Back-end >  In my code I got undefined while function returns true
In my code I got undefined while function returns true

Time:11-20

Function Definition

export const checkAuth = (accessToken) => {
const url = 'https://example/user-profile';
    console.log("We are in outer function");
    fetch(url, {
        method: 'GET',
        headers: new Headers({
            'Authorization' : 'Bearer '   accessToken,
        })
    }).then(res => res.json())
        .catch(function(error){
            console.error('Error : ', error)
        })

    .then((response) => {
            if(response.error != 'Unauthorized')
            {
                return true;
            }
            else{
                return false;
            }
    })
}

Function Calling

var res=checkAuth(this.state.accessToken);

In the res variable, I got undefined but I am passing true. How can I solve the problem?

CodePudding user response:

The checkAuth function isn't returning a value from the function. You are returning a value from the Promise chain, but that is the value that should be returned from checkAuth. You can simply return the Promise that fetch returns.

export const checkAuth = (accessToken) => {
  const url = 'https://example/user-profile';
  console.log("We are in outer function");
  return fetch(url, {
    method: 'GET',
    headers: new Headers({
      'Authorization' : 'Bearer '   accessToken,
    })
  }).then(res => res.json())
    .catch(function(error){
      console.error('Error : ', error)
    })
    .then((response) => {
      return response.error != 'Unauthorized'
    });
}

Because checkAuth now returns a Promise you will need to either call it in an async function and await the Promise to resolve, or chain from the returned Promise.

checkAuth(this.state.accessToken)
  .then(value => {
    // do something with value
  })
  .catch(error => {
    // handle any Promise rejections if they occur
  });
  • Related