Reputation: 173
I am making a function call from a useEffect
, the function is present in a different class. From that function I am calling another async function to make the ajax call after the promise is resolved, I am performing some operation on the data returned from the API call and then I am returning the data back to the useEffect
where the function is called in the first place. I am getting undefined in the useEffect
. Here is the code snippet
// In Main Class
let newObj=new ABC();
useEffect(()=>{
let flag= newObj.method1(url); //method present in another class.
setFlag(flag)
});
// Inside Class ABC
let flag;
method1(url){
this.method2(url).then(function(result) {
/*some operation */
flag=true; //set to true based on data
console.log(flag)//prints true
}
return flag // console log will print false here.
}
async method2(url){
let data=await axios.get(url);
return data;
}
The end result I am trying to get in the main class is true/false based on the API call, I want all the logic to be present in the class ABC.
Upvotes: 1
Views: 224
Reputation: 1247
You need to make your method1 which will return the promise, currently it is returning normal value instead of promise so you are getting undefined. Make your function look like below.
method1{
return new Promise(function(resolve, reject) {
this.method2(url).then(function(result) {
/*some operation */
flag=true; //set to true based on data
console.log(flag)//prints true
}
resolve(flag) // console log will print false here.
});
}
and change parent function like
let newObj=new ABC();
useEffect(()=>{
newObj.method1(url).then(flag =>{
setFlag(flag)
})
});
Upvotes: 2
Reputation: 21
useEffect(() => {
// Instead of using async at useEffect( async () => {}) Create a scoped async function in the hook
async function asynchronusFunction() {
await myFunction();
}
asynchronousFunction(); // call the above defined function now.
}, []);
You can create an async function call like the above method and use await to wait for the function to be exectuted. Using a async function means you are returning a promise. React does not wait for a promise : https://github.com/facebook/react/issues/1739
Upvotes: 0