Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
45
rated 0 times [  50] [ 5]  / answers: 1 / hits: 25215  / 4 Years ago, wed, march 18, 2020, 12:00:00

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;

More From » promise

 Answers
19

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;
}
}

[#51122] Friday, March 6, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jillalanisg

Total Points: 484
Total Questions: 98
Total Answers: 89

Location: Vanuatu
Member since Wed, Oct 14, 2020
4 Years ago
;