Mamun Labs Learn
JourneyGlossary
esc
  • Try “map”, “flexbox” or “state”.
Log in
Start learning
Phase 3 · 7 / 7Loading and error states
Phase 3JavaScript for real apps
7 topics · 3–4 wks
  1. 1Arrow functions
  2. 2Destructuring and spread
  3. 3Modules and npm
  4. 4Events and handlers
  5. 5Promises and await
  6. 6Fetching real data
  7. 7Loading and error states
JourneyPhase 3Loading and error states
01 / 09Overview

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.

Why it mattersReal internet is slow and sometimes gone. An app that shows a blank screen or spins forever feels broken, even when the code is fine.
about 60 min·needs: Fetching real data, Making decisions with if, Reading error messages
02 / 09

Watch & read

Start with the required ones. The others are there when you need them.

Article
Error handling, "try...catch"javascript.info · 20 min · English
MMamun's noteRead "The try…catch syntax", "Error object", "Throwing our own errors" and "try…catch…finally". Skip rethrowing and global catch.
Article
Async/await: error handlingjavascript.info · 5 min · English
MMamun's noteA short section showing try...catch around await, exactly the shape you'll use around fetch.
DocsOptional
Using the Fetch API: checking response statusMDN Web Docs · guide · 5 min · English
MMamun's noteRead only this section. It shows why fetch does not fail on a 404 and how response.ok fixes that.
VideoOptional
JavaScript Bangla tutorial #47: JavaScript errorsYouTube · Learn with Sumit · 22 min · Bangla
MMamun's noteIn Bangla. Sumit explains try, catch and finally with small examples. Watch it if the jump to catch still feels unclear.
03 / 09

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.

Words to recognise
loading stateerror statetry...catchfinallyresponse.okthrow
04 / 09

Code tour

Click a line number with a ring to read the note for that line.

script.js5 notes
let loading = true;
Mentor note · line 1
Three pieces of state. At the start you are loading, with no error and no data yet.
2let error = null;
3let data = null;
4async function loadWeather() {
try {
6 const response = await fetch(url);
if (!response.ok) throw new Error("Server said " + response.status);
8 data = await response.json();
9 } catch (err) {
error = "Could not load the weather. Check your internet.";
11 } finally {
loading = false;
13 }
14}
05 / 09

Practice

Short drills. Take your time and read the code before you answer.

DrillPredict1 / 2
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);
What does this print?
DrillFind the bug2 / 2
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.
1
2
3
4
Try 1 of 3 · solution unlocks after 3
06 / 09

Quick check

3 questions. Each one explains itself after you answer.

  1. 1 / 3The server answers 404 Not Found. What does await fetch(url) do?
  2. 2 / 3When does the finally block run?
  3. 3 / 3Inside try, the second line throws an error. What happens to the third line?
07 / 09

Explain it back

Only you can see this. Log in to keep it.0 words
08 / 09

How confident are you with Loading and error states?

09 / 09

Done

You can now
Read fetch code and say what the screen shows while loading, after an error and after success.
Next: Why types catch bugs Back to Phase 3
On this page
  1. 01Loading and error states
  2. 02Watch & read
  3. 03Explanation
  4. 04Code tour
  5. 05Practice
  6. 06Quick check
  7. 07Explain it back
  8. 08Confidence
  9. 09Done
Up next · 02 / 09Watch & read
Mamun Labs LearnFound a mistake on this page? Tell Mamun.
Mamun Labs Learn
JourneyGlossary
esc
  • Try “map”, “flexbox” or “state”.
Log in
Start learning
Log in to save your progress. Everything here works without an account.Log in to save progressLog in
Phase 3JavaScript for real apps
7 topics · 3–4 wks
  1. 1Arrow functions
  2. 2Destructuring and spread
  3. 3Modules and npm
  4. 4Events and handlers
  5. 5Promises and await
  6. 6Fetching real data
  7. 7Loading and error states
JourneyPhase 3Loading and error states
01 / 09Overview

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.

Why it mattersReal internet is slow and sometimes gone. An app that shows a blank screen or spins forever feels broken, even when the code is fine.
about 60 min·needs: Fetching real data, Making decisions with if, Reading error messages
02 / 09

Watch & read

Start with the required ones. The others are there when you need them.

Article
Error handling, "try...catch"javascript.info · 20 min · English
MMamun's noteRead "The try…catch syntax", "Error object", "Throwing our own errors" and "try…catch…finally". Skip rethrowing and global catch.
Article
Async/await: error handlingjavascript.info · 5 min · English
MMamun's noteA short section showing try...catch around await, exactly the shape you'll use around fetch.
DocsOptional
Using the Fetch API: checking response statusMDN Web Docs · guide · 5 min · English
MMamun's noteRead only this section. It shows why fetch does not fail on a 404 and how response.ok fixes that.
VideoOptional
JavaScript Bangla tutorial #47: JavaScript errorsYouTube · Learn with Sumit · 22 min · Bangla
MMamun's noteIn Bangla. Sumit explains try, catch and finally with small examples. Watch it if the jump to catch still feels unclear.
03 / 09

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.

Words to recognise
loading stateerror statetry...catchfinallyresponse.okthrow
04 / 09

Code tour

Click a line number with a ring to read the note for that line.

script.js5 notes
let loading = true;
Mentor note · line 1
Three pieces of state. At the start you are loading, with no error and no data yet.
2let error = null;
3let data = null;
4async function loadWeather() {
try {
6 const response = await fetch(url);
if (!response.ok) throw new Error("Server said " + response.status);
8 data = await response.json();
9 } catch (err) {
error = "Could not load the weather. Check your internet.";
11 } finally {
loading = false;
13 }
14}
05 / 09

Practice

Short drills. Take your time and read the code before you answer.

DrillPredict1 / 2
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);
What does this print?
DrillFind the bug2 / 2
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.
1
2
3
4
Try 1 of 3 · solution unlocks after 3
06 / 09

Quick check

3 questions. Each one explains itself after you answer.

  1. 1 / 3The server answers 404 Not Found. What does await fetch(url) do?
  2. 2 / 3When does the finally block run?
  3. 3 / 3Inside try, the second line throws an error. What happens to the third line?
07 / 09

Explain it back

Only you can see this. Log in to keep it.0 words
08 / 09

How confident are you with Loading and error states?

09 / 09

Done

You can now
Read fetch code and say what the screen shows while loading, after an error and after success.
Next: Why types catch bugs Back to Phase 3
On this page
  1. 01Loading and error states
  2. 02Watch & read
  3. 03Explanation
  4. 04Code tour
  5. 05Practice
  6. 06Quick check
  7. 07Explain it back
  8. 08Confidence
  9. 09Done
Up next · 02 / 09Watch & read

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.

Words to recognise
loading stateerror statetry...catchfinallyresponse.okthrow

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.

Words to recognise
loading stateerror statetry...catchfinallyresponse.okthrow