javascript / intermediate
Snippet
Handling Async Errors with try-catch in Hooks
Intermediate React development requires robust error handling within async effects to manage failed network requests and UI states.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
useEffect(() => {const fetchData = async () => {try {setLoading(true);const response = await fetch('/api/data');if (!response.ok) throw new Error('Network response was not ok');const json = await response.json();setData(json);} catch (err) {setError(err.message);} finally {setLoading(false);}};fetchData();}, []);
react
Breakdown
1
try { ... } catch (err)
Standard block for catching exceptions during asynchronous execution.
2
if (!response.ok) throw ...
Manually triggers an error for HTTP statuses like 404 or 500.
3
finally { setLoading(false) }
Ensures the loading state is reset regardless of whether the call succeeded or failed.