🎓 A1Learner
🔍
0 of 50 lessons completed

Showing Errors

An error state is a message that shows when a request fails. It tells the reader what went wrong in plain words.

An error in state

const [error, setError] = useState(null);

Showing the error

{error && <p>Could not load notes. Please try again.</p>}

Storing the error after a failed fetch

fetch('/api/notes')
  .catch(() => setError('Could not load notes.'));

Example

import { useState } from 'react';

export default function App() {
  const [error] = useState('Could not load notes.');

  return (
    <div>
      <h1>Notes</h1>
      {error && <p>{error}</p>}
    </div>
  );
}

Key points

  • An error lives in state, and it starts as null.
  • Null means that no error has happened yet.
  • The fetch catch block stores the error message in state.
  • Conditional rendering shows the error only when it is not null.

In this example, the error state holds a message, so the first render shows it under the heading. The list is not rendered, because the notes never arrived. In the real app, the catch block of the fetch stores this message when the request fails.

Note

The notes list stays hidden while an error shows.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Where does the error message live in the component?