UNPKG

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