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