Refreshing After a Change
Refreshing after a change is fetching the notes again once a change is done. The list then shows the true state of the server.
A loader for the notes
function loadNotes() {
return fetch(API_URL + '/notes').then((res) => res.json());
}Refreshing after a POST
fetch(API_URL + '/notes', { method: 'POST' }).then(() => loadNotes());Refreshing after a delete
fetch(API_URL + '/notes/' + id, { method: 'DELETE' }).then(() => loadNotes());Example
import { useState } from 'react';
export default function App() {
const [notes] = useState([
{ id: 1, title: 'Buy milk' },
{ id: 2, title: 'Ship MERN' },
{ id: 3, title: 'Read a book' },
]);
return (
<div>
<h1>Notes</h1>
<button>Refresh</button>
<ul>
{notes.map((note) => (
<li key={note.id}>{note.title}</li>
))}
</ul>
</div>
);
}Key points
- A change such as an add or a delete can leave local state out of step.
- Fetching again after the change brings back the fresh list.
- The fresh fetch runs after the POST, PUT, or DELETE finishes.
- The loading flag can show again while the fresh list loads.
In this example, the first render shows the three seed notes with a Refresh button above them. The button stands for the fresh fetch in the real app. After an add, an edit, or a delete, the app calls the loader again. The list then shows the true state of the server.
Note
A fresh fetch is simple and safe, even when the local update looks right.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
When does the app fetch the notes again?