Fetching Data from React
Fetching data from React is a request that a component sends when it appears. The component shows a loading line first, then the notes.
Fetching when the page loads
useEffect runs the request once, after the first render.
useEffect(() => {
fetch('/api/notes')
.then((res) => res.json())
.then((data) => setNotes(data));
}, []);A loading line
While the notes are missing, the page says so.
if (notes === null) {
return <p>Loading notes...</p>;
}Rendering the list
Each note becomes one list item.
{notes.map((note) => (
<li key={note.title}>{note.title}</li>
))}Example
import { useEffect, useState } from 'react';
export default function App() {
const [notes, setNotes] = useState(null);
useEffect(() => {
fetch('/api/notes')
.then((res) => res.json())
.then((data) => setNotes(data));
}, []);
if (notes === null) {
return <p>Loading notes...</p>;
}
return (
<ul>
{notes.map((note) => (
<li key={note.title}>{note.title}</li>
))}
</ul>
);
}Key points
- A component fetches data when it first appears on the page.
- useEffect runs the fetch once, after the first render.
- useState holds the notes, starting with no value.
- While the notes are missing, the page shows a loading line.
- When the data arrives, the state changes and the list appears.
In this example, the component keeps its notes in state, starting with no value. An effect runs once after the first render and asks /api/notes for the data. While the notes are missing, the component shows a loading line. The output is the first render, before the data arrives. When the data arrives, the state changes and the list appears.
Note
The empty pair of brackets after useEffect means the fetch runs only once.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does the page show before the notes arrive?