2

i want this function to return either true or false, instead I get

/**
 * Sends request to the backend to check if jwt is valid
 * @returns {boolean} 
 */
const isAuthenticated = () => {
    const token = localStorage.getItem('jwt'); 
    if(!token) return false; 
    const config = {headers : {'x-auth-token' : token}}; 

    const response = axios.get('http://localhost:8000/user' , config)
    .then(res =>  res.status === 200 ? true : false)
    .catch(err => false);

    return  response;
}   

export default isAuthenticated; 

I tried separating them and using async/await :

const isAuthenticated = async () => {
    const response = await makeRequest();
    return  response;
}   


const makeRequest = async () => { 
    const token = localStorage.getItem('jwt'); 
    const config = {headers : {'x-auth-token' : token}}; 
    const response = await axios.get('http://localhost:8000/user' , config)
    .then(res =>  res.status === 200 ? true : false)
    .catch(err => false);

    return response;
}

And still the same..

After some suggestions :

const isAuthenticated =  () => {
    const response =  makeRequest();
    return  response;
}   


const makeRequest = async () => { 
    try {
        const token = localStorage.getItem('jwt'); 
        const config = {headers : {'x-auth-token' : token}}; 
        const response = await axios.get('http://localhost:8000/user', config);
        if (response.status === 200) { // response - object, eg { status: 200, message: 'OK' }
            console.log('success stuff');
            return true;
        }
        return false;
   } catch (err) {
        console.error(err)
        return false;
   }
}
export default isAuthenticated; 
Kevin.a
  • 4,094
  • 8
  • 46
  • 82
  • 1
    `await` ~ `then` is a antipattern, you should to check about [async/await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) & [promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) – Christian Carrillo Mar 18 '20 at 13:21

2 Answers2

12

First of all if. If you are using the default promise then & catch, then the success action should be handled within the 'then' function.

axios.get('http://localhost:8000/user', config)
.then(res => console.log('succesfull stuff to be done here')
.catch(err => console.error(err)); // promise

if you want to use the async/await syntactic sugar, which I personally like it's

const makeRequest = async () => { 
    try {
    const token = localStorage.getItem('jwt'); 
    const config = {headers : {'x-auth-token' : token}}; 
    const response = await axios.get('http://localhost:8000/user', config);
    if (response.status === 200) { // response - object, eg { status: 200, message: 'OK' }
      console.log('success stuff');
     return true;
    }
    return false;
   } catch (err) {
     console.error(err)
     return false;
   }
}
Alex
  • 1,210
  • 3
  • 21
  • 34
  • it logs out the success stuff but I am interested in that true or false value, it is not returning true or false, but still Pending. I am doing `console.log(makeRequest())` Apologies if this is straight forward and i am just not getting it – Kevin.a Mar 18 '20 at 13:29
  • What approach are you going for? promise.then.catch or async/await? – Alex Mar 18 '20 at 13:47
  • if you are using promise.then.catch then you can't simply console.log(promise), you will get pending. what you CAN do it, inside of the promise.then() handle the status === 200 there – Alex Mar 18 '20 at 13:49
  • Async await, the example you posted. I will update the question with what i've tried so you can see. – Kevin.a Mar 18 '20 at 13:50
  • if you do it like this `.then(res => res.status === 200 ? true : false)` that means that you returning an boolean `true` or `false`. you can catch that with `.then(res => res.status === 200 ? true : false).then(boolValue => {console.log(boolValue)})` you should see now an true or false in the console. i hope that you are familiar with that syntax `(res => someValue)` thats the same like `(res => { return someValue; })` – bill.gates Mar 18 '20 at 13:56
  • I guess issue you are facing, is that you are trying to access a promise outside of an async func, if you really wanna to do that then use 'then' function. Also instead of status === 200 ? true : false, just use status === 200, because it will return either true of false either way. – Alex Mar 18 '20 at 13:59
0

You have to employ the use of async/await,like this:

const isAuthenticated =async () => {
const token = localStorage.getItem('jwt'); 
if(!token) return false; 
const config = {headers : {'x-auth-token' : token}}; 

const response =await axios.get('http://localhost:8000/user' , config)
.then(res =>  res.status === 200 ? true : false)
.catch(err => false);

return  response;

}

iSteven Zion
  • 11
  • 1
  • 2