I am new in ReactJS. I have a following function where an asynchronous function is called.
const ShowNodes = async function(e){
e.preventDefault();
try{
let count = await countNodes();
console.log("count::", count);
}
catch(error) {
console.error(error);
}
finally{
setValue(count);
}
}
Here countNodes() function returns a number and I want to display this number in console. But the variable count is not getting the value and console is showing undefined. Can you tell me how should I handle the values returned from an asynchronous function?
CodePudding user response:
The code itself seems to be working fine. you need to check countNodes
and make sure that it's returning the expected value
CodePudding user response:
Check the countNodes function and make sure that it's returning the expected value
CodePudding user response:
Hi there I think you need to shed more light on how you implemented the countNode function so we can check if it actually returns the right data I'm assuming the ShowNodes function is triggered by an event listener that gets triggered more than once and please show the JSX code where the ShowNodes function is being called. I think one problem here is scope because finally function cannot access the count you can try this solution.
const ShowNodes = async function(e){
e.preventDefault();
let count;
try{
count = await countNodes();
console.log("count::", count);
}
catch(error) {
console.error(error);
}
setValue(count);
}