Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

client-persist-demo.component.ts

84 lines2.2 KB

1import { ChangeDetectionStrategy, Component } from '@angular/core'
2import { injectQuery } from '@tanstack/angular-query'
3import { CLIENT_PERSIST_QUERY_ROOT } from '../query-persist-scope'
4​
5/**
6 * Mounted only in the browser (parent uses `afterNextRender`), so `queryFn` is not run during SSR.
7 * Pair with `dehydrateOptions.shouldDehydrateQuery` if you want only `client-persist` keys in storage.
8 */
9@Component({
10 changeDetection: ChangeDetectionStrategy.OnPush,
11 selector: 'client-persist-demo',
12 template: `
13 <div class="panel">
14 <p class="badge">Client-only island</p>
15 <h3>Client-only persisted query</h3>
16 @if (demo.isPending()) {
17 <p>Loading client-only data…</p>
18 } @else if (demo.isError()) {
19 <p>Failed to load.</p>
20 } @else if (demo.data(); as data) {
21 <p class="mono">{{ data.createdAt }}</p>
22 <p class="note">
23 This value is stored under the <code>client-persist</code> query key.
24 Hard-reload the page: it should reappear from persistence while the
25 posts list above is rendered from SSR again.
26 </p>
27 }
28 </div>
29 `,
30 styles: `
31 .panel {
32 margin-top: 8px;
33 padding: 20px;
34 border-radius: 18px;
35 border: 1px dashed #c4b5a0;
36 background: #fffefb;
37 }
38​
39 .badge {
40 margin: 0 0 8px;
41 font-size: 11px;
42 font-weight: 700;
43 letter-spacing: 0.1em;
44 text-transform: uppercase;
45 color: #7c5a10;
46 }
47​
48 h3 {
49 margin: 0 0 12px;
50 font-size: 1.1rem;
51 }
52​
53 .mono {
54 margin: 0 0 12px;
55 font-family: ui-monospace, monospace;
56 font-size: 0.85rem;
57 word-break: break-all;
58 }
59​
60 .note {
61 margin: 0;
62 font-size: 0.9rem;
63 line-height: 1.5;
64 color: #4b5563;
65 }
66​
67 code {
68 font-size: 0.88em;
69 padding: 0.1em 0.35em;
70 border-radius: 4px;
71 background: #f3f4f6;
72 }
73 `,
74})
75export class ClientPersistDemoComponent {
76 readonly demo = injectQuery(() => ({
77 queryKey: [CLIENT_PERSIST_QUERY_ROOT, 'timestamp-demo'],
78 queryFn: async () => {
79 await new Promise((r) => setTimeout(r, 100))
80 return { createdAt: new Date().toISOString() }
81 },
82 staleTime: Infinity,
83 }))