Reputation: 55
I'm very new to react I'm experimenting with the use-effect hook I'm trying to call and async function inside use effect something like this :
useEffect(() => {
async function fetchData() {
await new Promise(resolve => setTimeout(resolve, 1000));
console.log("done");
throw new error("error in here");
}
try {
fetchData();
}
catch(error){
console.log("error catching",error);
}
});
is this code the catch will not work since useEffect will return before fetchData
i'm aware that adding fetchData().catch(error => {console.log("error catched")});
will resolve the problem.
is this a correct solution or can i do better ?
Upvotes: 0
Views: 288
Reputation: 526
useEffect
callbacks are executed synchronously. Remember that, you can return a function in useEffect
callback. React will call that function, when it unmounts the component. So, if you want to use try/catch
, the you have to make the callback async
. When you do that, the callback returns a promise, instead of any value that you might return. In your case, you are not returning anything from the callback, so you can make it async and use try/catch
. Simply prefix await
before the fetchData
call. It would work. Or you can write a async function with try catch block and call that from the useEffect
callback. Previously it did not worked because, you did not awaited, when you called fetchData
The following things would work. In both scenarios, notice the await
keyword.
useEffect(async () => {
async function fetchData() {
await new Promise(resolve => setTimeout(resolve, 1000));
console.log("done");
throw new error("error in here");
}
try {
await fetchData();
}
catch(error){
console.log("error catching",error);
}
});
useEffect(() => {
loadData();
});
async function fetchData() {
await new Promise(resolve => setTimeout(resolve, 1000));
console.log("done");
throw new error("error in here");
}
async function loadData() {
try {
await fetchData();
}
catch(error){
console.log("error catching",error);
}
}
Upvotes: 0
Reputation: 29750
The React useEffect
hook does not support async
/await
. So you can't use a traditional try
/catch
as this is only supported for async/await style syntax. You'll need to use it like this:
useEffect(() => {
async function fetchData() {
await new Promise(resolve => setTimeout(resolve, 1000));
console.log("done");
throw new error("error in here");
}
fetchData().catch(err => {
console.log("error catching",error);
});
});
Upvotes: 1