I am trying to do a helper function to check if login or not in react and nodejs... in nodejs everything is fine but I have problems at reactside to get value outside of function with return:
return output always = undefined ...
Here is the function;
note: console.log (response) = {status: 200, data: true, error: false}
import axios from "axios";
import { useState,useEffect } from 'react';
export const AuthController = (event) => {
let data = {data : localStorage.getItem("imtakilogintoken")}
async function getData() {
try {
let res = await axios({
url: 'http://localhost:3005/profile',
method: 'post',
timeout: 8000,
data :data,
headers: {
'Content-Type': 'application/json',
}
})
return {
status : res.status,
data : res.data,
error : false
}
}
catch (err) {
return {
status : false,
data : false,
error : err
}
}
}
var output;
useEffect(() => {
getData().then(response => {
console.log (response)
output = response;
})
}, []);
return output;
}
CodePudding user response:
I think the problem itself is how you are trying to reach the data, on react I will recommend you to create a custom hook that you can implement on any component that loads later on the app, something like this:
import { useState, useCallback } from "react";
import axios from "axios";
const useAuthControl = () => {
const [hasResponse, setResponse] = useState(null);
const getData = useCallback(
async (data) => {
try {
let res = await axios({
url: 'http://localhost:3005/profile',
method: 'post',
timeout: 8000,
data :data,
headers: {
'Content-Type': 'application/json',
}
})
setResponse({
status : res.status,
data : res.data,
error : false
})
}
catch (err) {
setResponse({
status : false,
data : false,
error : err
})
}
},
[]
);
return [getData, {hasResponse}];
};
export default useAuthControl;
CodePudding user response:
For your kind information useEffect()
is async function, the control first going to return statement and at this time return output (undefined)
having undefined
.
I think here no need to wrap your function into useEffect()
instead just return from then only. so code would look like below.
import axios from "axios";
import { useState,useEffect } from 'react';
export const AuthController = (event) => {
let data = {data : localStorage.getItem("imtakilogintoken")}
async function getData() {
try {
let res = await axios({
url: 'http://localhost:3005/profile',
method: 'post',
timeout: 8000,
data :data,
headers: {
'Content-Type': 'application/json',
}
})
return {
status : res.status,
data : res.data,
error : false
}
}
catch (err) {
return {
status : false,
data : false,
error : err
}
}
}
//var output;
getData().then(response => {
console.log (response)
return response;
}).catch(err=>{
return err;
})
}