Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 13.5 — Data Routers: Loaders and Actions
React · Example 2 of 3

An action with Form, validation, redirect and revalidation

The empty submit runs the action, which returns an error object; the loader still re-runs (revalidation). The second submit saves and redirects; the loader runs again so the list shows the new todo. No useState for the list and no manual refetch. The input is uncontrolled: Form reads it by name.

In data mode you define routes as objects with createBrowserRouter (or createMemoryRouter) and render them with <RouterProvider>; each route can have a loader that fetches its data before it renders, an action that handles its <Form> submissions, and an errorElement for failures, while useNavigation() tells you when a navigation is pending.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Create a memory data router with a /posts route whose loader returns three post titles after 200 ms, and render them with useLoaderData.

02

Add a newsletter <Form method="post"> with an email field to a route; the action returns { error } when the email has no @, and { ok: true } otherwise. Show the right message.

03

Make a /posts/:id loader throw a 404 response for unknown ids and show Post not found from an errorElement.

Explain it without notes

01

What problem do loaders solve compared with fetching in useEffect?

02

Walk through what happens when a <Form method="post"> is submitted in a data router.

03

How do you show pending UI during navigations, and why does the old page stay visible?

04

How do errors work in data routers, and how do you tell a 404 from a crash?

An action with Form, validation, redirect and revalidation

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

loader: reading 1 todos
action: POST ""
loader: reading 1 todos
error shown: Please type a title
action: POST "Write an action"
loader: reading 2 todos
list: Learn routes, Write an action | url: /todos?added=Write%20an%20action