const getData = async () => {
try {
setLoading(true);
const response = await fetch(
"https://jsonplaceholder.typicode.com/posts"
);
// if error occurs here, then all the statements
//in the try block below this wont run.
// Hence cannot turn off loading here.
const data = await response.json();
setData(data);
} catch (error) {
console.log(error);
setToastMessage(error);
} finally {
setLoading(false); // Turn off loading irrespective of the status.
}
};
getData();
Thanks for reading π
Follow @codedrops.tech for daily posts.
Instagram β Twitter β Facebook
Micro-Learning β Web Development β Javascript β MERN stack β Javascript
codedrops.tech
Top comments (5)
Example is missing some important information...
The fetch API does not 'throw' errors, so this example is not 'catching' anything.
if (!response.ok) { throw Error(response.statusText) }
From the docs:
A fetch() promise only rejects when a network error is encountered (which is usually when thereβs a permissions issue or similar). A fetch() promise does not reject on HTTP errors (404, etc.). Instead, a then() handler must check the Response.ok and/or Response.status properties.
and what do you need
finally
for?In
finally
block you can perform things in all the cases. An error occurs or not thefinally
is executed. Ex., Turn offloading
.yes, but you actually don't need the
finally
block for that. you can callsetLoading(false)
directly below thecatch
block.do you think it looks just better? or is more clear?
You need it in try also then. And btw just an example. What if you need to execute more than 1 statement after the process. I cant copy paste in both try and catch block.