-
-
Notifications
You must be signed in to change notification settings - Fork 94
/
useSuspense.md
391 lines (306 loc) · 10.7 KB
/
useSuspense.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
---
title: useSuspense() - Simplified data fetching for React
sidebar_label: useSuspense()
description: High performance async data rendering without overfetching. useSuspense() is like await for React components.
---
<head>
<meta name="docsearch:pagerank" content="10"/>
</head>
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
import GenericsTabs from '@site/src/components/GenericsTabs';
import ConditionalDependencies from '../shared/\_conditional_dependencies.mdx';
import PaginationDemo from '../shared/\_pagination.mdx';
import HooksPlayground from '@site/src/components/HooksPlayground';
import { RestEndpoint } from '@data-client/rest';
import TypeScriptEditor from '@site/src/components/TypeScriptEditor';
import StackBlitz from '@site/src/components/StackBlitz';
import { detailFixtures, listFixtures } from '@site/src/fixtures/profiles';
# useSuspense()
<p class="tagline">
High performance async data rendering without overfetching.
</p>
`useSuspense()` is like [await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await) for React components. This means the remainder of the component only runs after the data has loaded, avoiding the complexity of handling loading and error conditions. Instead, fallback handling is
[centralized](../getting-started/data-dependency.md#boundaries) with a singular [AsyncBoundary](../api/AsyncBoundary.md).
`useSuspense()` is reactive to data [mutations](../getting-started/mutations.md); rerendering only when necessary.
## Usage
<Tabs
defaultValue="rest"
groupId="protocol"
values={[
{ label: 'Rest', value: 'rest' },
{ label: 'Promise', value: 'other' },
]}>
<TabItem value="rest">
<HooksPlayground fixtures={detailFixtures} row>
```typescript title="ProfileResource" collapsed
import { Entity, resource } from '@data-client/rest';
export class Profile extends Entity {
id: number | undefined = undefined;
avatar = '';
fullName = '';
bio = '';
static key = 'Profile';
}
export const ProfileResource = resource({
path: '/profiles/:id',
schema: Profile,
});
```
```tsx title="ProfileDetail"
import { useSuspense } from '@data-client/react';
import { ProfileResource } from './ProfileResource';
function ProfileDetail(): JSX.Element {
const profile = useSuspense(ProfileResource.get, { id: 1 });
return (
<div className="listItem">
<Avatar src={profile.avatar} />
<div>
<h4>{profile.fullName}</h4>
<p>{profile.bio}</p>
</div>
</div>
);
}
render(<ProfileDetail />);
```
</HooksPlayground>
</TabItem>
<TabItem value="other">
<HooksPlayground row>
```typescript title="Profile" collapsed
import { Endpoint } from '@data-client/endpoint';
export const getProfile = new Endpoint(
(id: number) =>
Promise.resolve({
id,
fullName: 'Jing Chen',
bio: 'Creator of Flux Architecture',
avatar: 'https://avatars.githubusercontent.com/u/5050204?v=4',
}),
{
key(id) {
return `getProfile${id}`;
},
},
);
```
```tsx title="ProfileDetail"
import { useSuspense } from '@data-client/react';
import { getProfile } from './Profile';
function ProfileDetail(): JSX.Element {
const profile = useSuspense(getProfile, 1);
return (
<div className="listItem">
<Avatar src={profile.avatar} />
<div>
<h4>{profile.fullName}</h4>
<p>{profile.bio}</p>
</div>
</div>
);
}
render(<ProfileDetail />);
```
</HooksPlayground>
</TabItem>
</Tabs>
## Behavior
Cache policy is [Stale-While-Revalidate](https://tools.ietf.org/html/rfc5861) by default but also [configurable](../concepts/expiry-policy.md).
| Expiry Status | Fetch | Suspend | Error | Conditions |
| ------------- | --------------- | ------- | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Invalid | yes<sup>1</sup> | yes | no | not in store, [deletion](/rest/api/resource#delete), [invalidation](./Controller.md#invalidate), [invalidIfStale](../concepts/expiry-policy.md#endpointinvalidifstale) |
| Stale | yes<sup>1</sup> | no | no | (first-render, arg change) & [expiry < now](../concepts/expiry-policy.md) |
| Valid | no | no | maybe<sup>2</sup> | fetch completion |
| | no | no | no | `null` used as second argument |
:::note
1. Identical fetches are automatically deduplicated
2. [Hard errors](../concepts/error-policy.md#hard) to be [caught](../getting-started/data-dependency#async-fallbacks) by [Error Boundaries](./AsyncBoundary.md)
:::
:::info React Native
When using React Navigation, useSuspense() will trigger fetches on focus if the data is considered
stale.
:::
<ConditionalDependencies />
## Types
<GenericsTabs>
```typescript
function useSuspense(
endpoint: ReadEndpoint,
...args: Parameters<typeof endpoint> | [null]
): Denormalize<typeof endpoint.schema>;
```
```typescript
function useSuspense<
E extends EndpointInterface<
FetchFunction,
Schema | undefined,
undefined
>,
Args extends readonly [...Parameters<E>] | readonly [null],
>(
endpoint: E,
...args: Args
): E['schema'] extends Exclude<Schema, null>
? Denormalize<E['schema']>
: ReturnType<E>;
```
</GenericsTabs>
## Examples
### List
<HooksPlayground fixtures={listFixtures} row>
```typescript title="ProfileResource" collapsed
import { Entity, resource } from '@data-client/rest';
export class Profile extends Entity {
id: number | undefined = undefined;
avatar = '';
fullName = '';
bio = '';
static key = 'Profile';
}
export const ProfileResource = resource({
path: '/profiles/:id',
schema: Profile,
});
```
```tsx title="ProfileList" {5}
import { useSuspense } from '@data-client/react';
import { ProfileResource } from './ProfileResource';
function ProfileList(): JSX.Element {
const profiles = useSuspense(ProfileResource.getList);
return (
<div>
{profiles.map(profile => (
<div className="listItem" key={profile.pk()}>
<Avatar src={profile.avatar} />
<div>
<h4>{profile.fullName}</h4>
<p>{profile.bio}</p>
</div>
</div>
))}
</div>
);
}
render(<ProfileList />);
```
</HooksPlayground>
### Pagination
Reactive [pagination](/rest/guides/pagination) is achieved with [mutable schemas](/rest/api/Collection)
<PaginationDemo defaultTab="PostList" />
### Sequential
When fetch parameters depend on data from another resource.
```tsx
function PostWithAuthor() {
const post = useSuspense(PostResource.get, { id });
const author = useSuspense(UserResource.get, {
// highlight-next-line
id: post.userId,
});
}
```
### Conditional
`null` will avoid binding and fetching data
<TypeScriptEditor row={false}>
```ts title="Resources" collapsed
import { Entity, resource } from '@data-client/rest';
export class Post extends Entity {
id = 0;
userId = 0;
title = '';
body = '';
static key = 'Post';
}
export const PostResource = resource({
path: '/posts/:id',
schema: Post,
});
export class User extends Entity {
id = 0;
name = '';
username = '';
email = '';
phone = '';
website = '';
get profileImage() {
return `https://i.pravatar.cc/64?img=${this.id + 4}`;
}
static key = 'User';
}
export const UserResource = resource({
urlPrefix: 'https://jsonplaceholder.typicode.com',
path: '/users/:id',
schema: User,
});
```
```tsx title="PostWithAuthor" {7-11}
import { PostResource, UserResource } from './Resources';
export default function PostWithAuthor({ id }: { id: string }) {
const post = useSuspense(PostResource.get, { id });
const author = useSuspense(
UserResource.get,
post.userId
? {
id: post.userId,
}
: null,
);
// author as User | undefined
if (!author) return;
}
```
</TypeScriptEditor>
### Embedded data
When entities are stored in [nested structures](/rest/guides/relational-data#nesting), that structure will remain.
<TypeScriptEditor row={false}>
```typescript title="api/Post" {12-16}
export class PaginatedPost extends Entity {
id = '';
title = '';
content = '';
static key = 'PaginatedPost';
}
export const getPosts = new RestEndpoint({
path: '/post',
searchParams: { page: '' },
schema: {
posts: new schema.Collection([PaginatedPost]),
nextPage: '',
lastPage: '',
},
});
```
```tsx title="ArticleList" {5-7}
import { getPosts } from './api/Post';
export default function ArticleList({ page }: { page: string }) {
const {
posts,
nextPage,
lastPage,
} = useSuspense(getPosts, { page });
return (
<div>
{posts.map(post => (
<div key={post.pk()}>{post.title}</div>
))}
</div>
);
}
```
</TypeScriptEditor>
### Server Side Rendering
[Server Side Rendering](../guides/ssr.md) to incrementally stream HTML,
greatly reducing [TTFB](https://web.dev/ttfb/). [Reactive Data Client SSR's](../guides/ssr.md) automatic store hydration
means immediate user interactivity with **zero** client-side fetches on first load.
<StackBlitz app="nextjs" file="resources/TodoResource.ts,components/todo/TodoList.tsx" />
Usage in components is identical, which means you can easily share components between SSR and non-SSR
applications, as well as migrate to <abbr title="Server Side Render">SSR</abbr> without needing data-client code changes.
### Concurrent Mode
In React 18 navigating with `startTransition` allows [AsyncBoundaries](./AsyncBoundary.md) to
continue showing the previous screen while the new data loads. Combined with
[streaming server side rendering](../guides/ssr.md), this eliminates the need to flash annoying
loading indicators - improving the user experience.
Click one of the names to navigate to their todos. Here long loading states are indicated by the
less intrusive _loading bar_, like [YouTube](https://youtube.com) and [Robinhood](https://robinhood.com) use.
<StackBlitz app="todo-app" file="src/pages/Home/TodoList.tsx,src/pages/Home/index.tsx,src/useNavigationState.ts" height={600} />
If you need help adding this to your own custom router, check out the [official React guide](https://react.dev/reference/react/useTransition#building-a-suspense-enabled-router)