Loading and error states
You'll learn to show the three states of any fetch: loading, error and data, and to catch failures with try...catch.
Watch & read
Start with the required ones. The others are there when you need them.
Explanation
Your weather page works on your Wi-Fi. Then a friend opens it on a slow mobile connection in a bus, and sees a blank screen. Or the internet drops, and nothing happens at all. Real apps plan for this.
Think of sending money with bKash. You see "Processing...", then either "Transaction successful" or "Transaction failed, try again". Never a blank screen. Every request in your app has the same three states: loading, error, and data.
let loading = true;let error = null;let data = null;
When code might fail, wrap it in try...catch. JavaScript runs the try block. If anything in it
fails, it jumps straight to catch, with the error. finally runs at the end either way:
try {const response = await fetch(url);if (!response.ok) throw new Error("Server said " + response.status);data = await response.json();} catch (err) {error = err.message;} finally {loading = false;}
Two things here surprise people. First, fetch only fails by itself when there is no connection at all.
If the server answers "404, not found", fetch still succeeds. So you check response.ok, which is
true only for good answers, and throw your own error when it is false.
Second, people often write loading = false as the last line of try. When an error happens, that line
is skipped, and the spinner turns forever. Put it in finally, which always runs.
Then the screen just follows the state: if loading, show "Loading...". Else if error, show a message
and a "Try again" button. Else show the data. Write the error message for people, not for developers:
"Could not load the weather. Check your internet." beats "TypeError: Failed to fetch".
When you read fetch code, ask: what does the screen show while it waits, and what does it show if it fails? If either answer is "nothing", you've found a bug.
Code tour
Click a line number with a ring to read the note for that line.
Practice
Short drills. Take your time and read the code before you answer.
1let loading = true;2try {3 throw new Error("No internet");4 loading = false;5} catch (err) {6 console.log("Error:", err.message);7}8console.log("loading:", loading);
message gets the state of a weather request and returns the text to show. It works while loading and after success, but crashes after an error. Fix it so all three checks pass.Quick check
3 questions. Each one explains itself after you answer.
- 1 / 3The server answers
404 Not Found. What doesawait fetch(url)do? - 2 / 3When does the
finallyblock run? - 3 / 3Inside
try, the second line throws an error. What happens to the third line?