Skip to content

Commit b708b4d

Browse files
Update response helpers documentation (#1331)
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
1 parent 3315d78 commit b708b4d

File tree

3 files changed

+251
-95
lines changed

3 files changed

+251
-95
lines changed

src/routes/solid-router/reference/response-helpers/json.mdx

Lines changed: 115 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -7,38 +7,134 @@ tags:
77
- json
88
- api
99
- actions
10-
- cache
10+
- queries
1111
- revalidation
1212
- response
13-
version: '1.0'
13+
version: "1.0"
1414
description: >-
15-
Return JSON data from actions with cache revalidation control. Configure how
15+
Return JSON data from actions with query revalidation control. Configure how
1616
route data updates after mutations for optimal performance.
1717
---
1818

19-
Returns JSON data from an action while also providing options for controlling revalidation of cache data on the route.
19+
The `json` function returns a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) object that contains the provided data.
20+
It is intended for sending JSON data from a [query](/solid-router/reference/data-apis/query) or [action](/solid-router/concepts/actions) while also allowing configuration of query revalidation.
2021

21-
```ts title="/actions/get-completed-todos.ts" {7}
22-
import { action, json } from "@solidjs/router";
23-
import { fetchTodo } from "../fetchers";
22+
This works both in client and server (e.g., using a server function) environments.
2423

25-
const getCompletedTodos = action(async () => {
26-
const completedTodos = await fetchTodo({ status: 'complete' });
24+
## Import
2725

28-
return json(completedTodos, { revalidate: getTodo.keyFor(id) });
29-
});
26+
```ts
27+
import { json } from "@solidjs/router";
3028
```
3129

32-
Also read [action](/solid-router/reference/data-apis/action) and [revalidate](/solid-router/reference/response-helpers/revalidate).
30+
## Type
3331

34-
## Type Signature
32+
```ts
33+
function json<T>(
34+
data: T,
35+
init: {
36+
revalidate?: string | string[];
37+
headers?: HeadersInit;
38+
status?: number;
39+
statusText?: string;
40+
} = {}
41+
): CustomResponse<T>;
42+
```
43+
44+
## Parameters
45+
46+
### `data`
47+
48+
- **Type:** `T`
49+
- **Required:** Yes
50+
51+
The data to be serialized as JSON in the response body.
52+
It must be a value that can be serialized with [`JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify).
53+
54+
### `init`
55+
56+
- **Type:** `{ revalidate?: string | string[]; headers?: HeadersInit; status?: number; statusText?: string; }`
57+
- **Required:** No
58+
59+
An optional configuration object with the following properties:
60+
61+
#### `revalidate`
62+
63+
- **Type:** `string | string[]`
64+
- **Required:** No
65+
66+
A query key or an array of query keys to revalidate.
67+
Passing an empty array (`[]`) disables query revalidation entirely.
68+
69+
#### `headers`
70+
71+
- **Type:** `HeadersInit`
72+
- **Required:** No
73+
74+
An object containing any headers to be sent with the response.
75+
76+
#### `status`
3577

36-
```typescript
37-
interface ResponseOptions & Omit<ResponseInit, "body"> {
38-
revalidate?: string | string[];
78+
- **Type:** `number`
79+
- **Required:** No
80+
81+
The HTTP status code of the response.
82+
Defaults to [`200 OK`](http://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/200).
83+
84+
#### `statusText`
85+
86+
- **Type:** `string`
87+
- **Required:** No
88+
89+
The status text associated with the status code.
90+
91+
## Examples
92+
93+
### Invalidating Data After a Mutation
94+
95+
```tsx
96+
import { For } from "solid-js";
97+
import { query, action, json, createAsync } from "@solidjs/router";
98+
99+
const getCurrentUserQuery = query(async () => {
100+
return await fetch("/api/me").then((response) => response.json());
101+
}, "currentUser");
102+
103+
const getPostsQuery = query(async () => {
104+
return await fetch("/api/posts").then((response) => response.json());
105+
}, "posts");
106+
107+
const createPostAction = action(async (formData: FormData) => {
108+
const title = formData.get("title")?.toString();
109+
const newPost = await fetch("/api/posts", {
110+
method: "POST",
111+
body: JSON.stringify({ title }),
112+
}).then((response) => response.json());
113+
114+
// Only revalidate the "posts" query.
115+
return json(newPost, { revalidate: "posts" });
116+
}, "createPost");
117+
118+
function Posts() {
119+
const currentUser = createAsync(() => getCurrentUserQuery());
120+
const posts = createAsync(() => getPostsQuery());
121+
122+
return (
123+
<div>
124+
<p>Welcome back {currentUser()?.name}</p>
125+
<ul>
126+
<For each={posts()}>{(post) => <li>{post.title}</li>}</For>
127+
</ul>
128+
<form action={createPostAction} method="post">
129+
<input name="title" />
130+
<button>Create Post</button>
131+
</form>
132+
</div>
133+
);
39134
}
135+
```
40136

41-
json<T>(data: T, opt?: ResponseOptions): CustomResponse<T>;
42-
```
137+
## Related
43138

44-
The `ResponseOptions` extens the types from the native [`ResponseInit`](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#options) interface.
139+
- [`query`](/solid-router/reference/data-apis/query)
140+
- [`action`](/solid-router/reference/data-apis/action)

src/routes/solid-router/reference/response-helpers/redirect.mdx

Lines changed: 73 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -10,89 +10,106 @@ tags:
1010
- routing
1111
- authorization
1212
- forms
13-
version: '1.0'
13+
version: "1.0"
1414
description: >-
1515
Redirect users between routes with proper status codes. Handle authentication
1616
flows, form submissions, and protected route access.
1717
---
1818

19-
Redirects to the next route.
20-
When done over a server RPC (Remote Procedure Call), the redirect will be done through the server.
21-
By default the status code of a `redirect()` is `302 - FOUND`, also known as a temporary redirect.
19+
The `redirect` function returns a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) object that instructs the router to navigate to a different route when returned or thrown from a [query](/solid-router/reference/data-apis/query) or [action](/solid-router/concepts/actions).
2220

23-
Other useful redirect codes:
21+
This works both in client and server (e.g., using a server function) environments.
2422

25-
| Code | Description |
26-
| ---- | ----------- |
27-
| `301` | Moved Permanently |
28-
| `307` | Temporary Redirect |
29-
| `308` | Permanent redirect |
23+
## Import
3024

31-
:::tip[Redirect Methods]
32-
307 and 308 won't allow the browser to change the method of the request.
33-
If you want to change the method, you should use 301 or 302.
34-
:::
25+
```ts
26+
import { redirect } from "@solidjs/router";
27+
```
3528

36-
A common use-case for throwing a redirect is when a user is not authenticated and needs to be sent to the login page or another public route.
29+
## Type
3730

38-
```js title="/queries/get-user.ts" {7}
39-
import { query, redirect } from "@solidjs/router";
40-
import { getCurrentUser } from "../auth";
41-
42-
const getUser = query(() => {
43-
const user = await getCurrentUser();
44-
45-
if (!user) throw redirect("/login");
46-
47-
return user;
48-
}, "get-user")
31+
```ts
32+
function redirect(
33+
url: string,
34+
init?:
35+
| number
36+
| {
37+
revalidate?: string | string[];
38+
headers?: HeadersInit;
39+
status?: number;
40+
statusText?: string;
41+
}
42+
): CustomResponse<never>;
4943
```
5044

51-
## Single-Flight Mutations
45+
## Parameters
5246

53-
When using `redirect` during a Server Action, the redirect will be done through the server.
54-
The response value will automatically send data for the destination route, avoiding a subsequent roundtrip to load the data from the target route.
47+
### `url`
5548

56-
This is useful when redirecting the user to a different route once a mutation is done.
49+
- **Type:** `string`
50+
- **Required:** Yes
5751

58-
```ts title="/actions/add-user.ts" {3,6}
59-
import { action, redirect } from "@solidjs/router";
52+
The absolute or relative URL to which the redirect should occur.
6053

61-
const addUser = action(async (user: User) => {
62-
await postUser(user);
63-
64-
return redirect("/users");
65-
});
66-
```
54+
### `init`
6755

68-
The `addUser` action will redirect the user to the `/users` route once the user has been added to the database.
69-
The response from the form action will send the updated data for the `/users` route without the developer needing to revalidate or reload.
56+
- **Type:** `number | { revalidate?: string | string[]; headers?: HeadersInit; status?: number; statusText?: string; }`
57+
- **Required:** No
7058

71-
## Throw vs Return
59+
Either a number representing the status code or a configuration object with the following properties:
7260

73-
Both `throw` and `return` can be used to redirect the user to a different route.
74-
For general usage `throw` is recommended as it immediately stops the execution of the current action and redirects the user.
61+
#### `revalidate`
7562

76-
When returning from a nested method, the parent method will continue to execute, which can lead to unexpected behavior.
63+
- **Type:** `string | string[]`
64+
- **Required:** No
7765

78-
### TypeScript Signature
66+
A query key or an array of query keys to revalidate on the destination route.
7967

80-
```typescript
81-
type RouterResponseInit = Omit<ResponseInit, "body"> & {
82-
revalidate?: string | string[];
83-
};
68+
#### `status`
8469

85-
function redirect(url: string, init?: number | RouterResponseInit): CustomResponse<never>;
86-
```
70+
- **Type:** `number`
71+
- **Required:** No
8772

88-
The `RouterResponseInit` type extends the native [`ResponseInit`](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#options) interface.
73+
The HTTP status code for the redirect.
74+
Defaults to [`302 Found`)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/302).
8975

90-
## Revalidate Query Keys
76+
## Examples
9177

92-
You can pass query keys to the redirect helper to revalidate them.
78+
### Basic Usage
9379

9480
```ts
95-
redirect("/", { revalidate: ["getUser", getUser.keyFor(id)] });
81+
import { query, redirect } from "@solidjs/router";
82+
83+
const getCurrentUserQuery = query(async () => {
84+
const response = await fetch("/api/me");
85+
86+
if (response.status === 401) {
87+
return redirect("/login");
88+
}
89+
90+
return await response.json();
91+
}, "currentUser");
9692
```
9793

98-
This will only invalidate the query keys passed to the redirect helper instead of the entire next page.
94+
### Configuring Query Revalidation
95+
96+
```ts
97+
import { action, redirect } from "@solidjs/router";
98+
99+
const loginAction = action(async (formData: FormData) => {
100+
const username = formData.get("username")?.toString();
101+
const password = formData.get("password")?.toString();
102+
103+
await fetch("/api/login", {
104+
method: "POST",
105+
body: JSON.stringify({ username, password }),
106+
}).then((response) => response.json());
107+
108+
return redirect("/users", { revalidate: ["currentUser"] });
109+
}, "login");
110+
```
111+
112+
## Related
113+
114+
- [`query`](/solid-router/reference/data-apis/query)
115+
- [`action`](/solid-router/reference/data-apis/action)

0 commit comments

Comments
 (0)