Adding Fetch Notes Functionality to CloudNotebook App ๐โ๏ธ
So far, CloudNotebook has been working with static, hardcoded notes stored directly
in component state. In a real app, notes live on a server or database, and our
React app needs to fetch them over the network when the page loads.
In this tutorial, we will learn:
notes, loading, and error to component statefetchNotes() function using the Fetch APIfetchNotes() on mount with useEffectWhat Does "Fetching Notes" Mean?
Fetching means asking a server for data over the network โ in our case, the list of notes
a user has saved in CloudNotebook. The browser's built-in fetch() function sends a
request to an API endpoint (like /api/notes) and returns a Promise that resolves
with the response. Because this takes time and can fail, we need to track three things:
whether we're still loading, whether an error occurred, and the actual notes data
once it arrives.
Step 1: Add notes, loading, and error to State
Open your Notes.js component and set up state using the useState hook to
track our three key pieces of data.
import React, { useState, useEffect } from "react";
import NoteItem from "./NoteItem";
import Spinner from "./Spinner";
const Notes = () => {
const [notes, setNotes] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
return (
<div className="container my-4">
<h2 className="text-center mb-4">My CloudNotebook ๐</h2>
</div>
);
};
export default Notes;
Step 2: Write an Async fetchNotes Function
Next, let's write a function that calls our notes API using fetch() with
async/await. We wrap it in a try/catch block so network failures don't
crash the app.
const fetchNotes = async () => {
setLoading(true);
setError(null);
try {
const response = await fetch("https://api.cloudnotebook.com/notes");
if (!response.ok) {
throw new Error("Failed to fetch notes. Please try again.");
}
const data = await response.json();
setNotes(data);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
Step 3: Call fetchNotes on Mount with useEffect
We only want to fetch notes once, right when the component first renders โ not on
every re-render. The useEffect hook with an empty dependency array
([]) handles this perfectly.
useEffect(() => {
fetchNotes();
}, []);
Step 4: Render Loading, Error, and Notes States
Now let's update render logic (JSX) to show the Spinner while loading,
an error message if something went wrong, or the list of notes once they're ready.
return (
<div className="container my-4">
<h2 className="text-center mb-4">My CloudNotebook ๐</h2>
{loading && <Spinner />}
{!loading && error && (
<div className="alert alert-danger text-center">{error}</div>
)}
{!loading && !error && notes.length === 0 && (
<p className="text-center text-muted">No notes yet. Create your first note!</p>
)}
{!loading && !error &&
notes.map((note) => (
<NoteItem
key={note.id}
title={note.title}
content={note.content}
createdAt={note.createdAt}
/>
))}
</div>
);
Step 5: Full Updated Notes.js
Here is the complete Notes.js component with state, the fetch function, and
conditional rendering all combined.
import React, { useState, useEffect } from "react";
import NoteItem from "./NoteItem";
import Spinner from "./Spinner";
const Notes = () => {
const [notes, setNotes] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const fetchNotes = async () => {
setLoading(true);
setError(null);
try {
const response = await fetch("https://api.cloudnotebook.com/notes");
if (!response.ok) {
throw new Error("Failed to fetch notes. Please try again.");
}
const data = await response.json();
setNotes(data);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchNotes();
}, []);
return (
<div className="container my-4">
<h2 className="text-center mb-4">My CloudNotebook ๐</h2>
{loading && <Spinner />}
{!loading && error && (
<div className="alert alert-danger text-center">{error}</div>
)}
{!loading && !error && notes.length === 0 && (
<p className="text-center text-muted">No notes yet. Create your first note!</p>
)}
{!loading && !error &&
notes.map((note) => (
<NoteItem
key={note.id}
title={note.title}
content={note.content}
createdAt={note.createdAt}
/>
))}
</div>
);
};
export default Notes;
How the Fetch States Work Together
| State Value | Meaning | What Renders |
|---|---|---|
loading = true |
Request is in progress | Spinner only |
error โ null |
Request failed (network issue, bad response, etc.) | Red alert message with error text |
notes.length === 0 |
Request succeeded but the user has no notes yet | Friendly empty-state message |
notes.length > 0 |
Request succeeded with data | List of NoteItem components |
Features and Learnings:-
notes, loading, and error to component state using useState.fetchNotes() function using the Fetch API and try/catch.useEffect with an empty dependency array to fetch notes once on mount..map() and a NoteItem component.