| 1 | ---
|
| 2 | title: Status Codes
|
| 3 | ---
|
| 4 |
|
| 5 | # Status Codes
|
| 6 |
|
| 7 | [MODES: framework ,data]
|
| 8 |
|
| 9 | <br/>
|
| 10 | <br/>
|
| 11 |
|
| 12 | Set status codes from loaders and actions with `data`.
|
| 13 |
|
| 14 | ```tsx filename=app/project.tsx lines=[3,12-15,20,23]
|
| 15 | // route('/projects/:projectId', './project.tsx')
|
| 16 | import type { Route } from "./+types/project";
|
| 17 | import { data } from "react-router";
|
| 18 | import { fakeDb } from "../db";
|
| 19 |
|
| 20 | export async function action({
|
| 21 | request,
|
| 22 | }: Route.ActionArgs) {
|
| 23 | let formData = await request.formData();
|
| 24 | let title = formData.get("title");
|
| 25 | if (!title) {
|
| 26 | return data(
|
| 27 | { message: "Invalid title" },
|
| 28 | { status: 400 },
|
| 29 | );
|
| 30 | }
|
| 31 |
|
| 32 | if (!projectExists(title)) {
|
| 33 | let project = await fakeDb.createProject({ title });
|
| 34 | return data(project, { status: 201 });
|
| 35 | } else {
|
| 36 | let project = await fakeDb.updateProject({ title });
|
| 37 | // the default status code is 200, no need for `data`
|
| 38 | return project;
|
| 39 | }
|
| 40 | }
|
| 41 | ```
|
| 42 |
|
| 43 | See [Form Validation](./form-validation) for more information on rendering form errors like this.
|
| 44 |
|
| 45 | Another common status code is 404:
|
| 46 |
|
| 47 | ```tsx
|
| 48 | // route('/projects/:projectId', './project.tsx')
|
| 49 | import type { Route } from "./+types/project";
|
| 50 | import { data } from "react-router";
|
| 51 | import { fakeDb } from "../db";
|
| 52 |
|
| 53 | export async function loader({ params }: Route.ActionArgs) {
|
| 54 | let project = await fakeDb.getProject(params.id);
|
| 55 | if (!project) {
|
| 56 | // throw to ErrorBoundary
|
| 57 | throw data(null, { status: 404 });
|
| 58 | }
|
| 59 | return project;
|
| 60 | }
|
| 61 | ```
|
| 62 |
|
| 63 | See the [Error Boundaries](./error-boundary) for more information on thrown `data`.
|