UNPKG

1.51 kB Markdown View Raw
1---
2title: Status Codes
3---
4
5# Status Codes
6
7[MODES: framework ,data]
8
9Set 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')
13import type { Route } from "./+types/project";
14import { data } from "react-router";
15import { fakeDb } from "../db";
16
17export 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
40See [Form Validation](./form-validation) for more information on rendering form errors like this.
41
42Another common status code is 404:
43
44```tsx
45// route('/projects/:projectId', './project.tsx')
46import type { Route } from "./+types/project";
47import { data } from "react-router";
48import { fakeDb } from "../db";
49
50export 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
60See the [Error Boundaries](./error-boundary) for more information on thrown `data`.