Skip to content

Commit f1b1b78

Browse files
committed
docs
1 parent 3e43af5 commit f1b1b78

File tree

109 files changed

+8125
-78
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

109 files changed

+8125
-78
lines changed

docs/framework/preact/comparison.md

Lines changed: 111 additions & 0 deletions
Large diffs are not rendered by default.

docs/framework/preact/devtools.md

Lines changed: 196 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,196 @@
1+
---
2+
id: devtools
3+
title: Devtools
4+
---
5+
6+
Wave your hands in the air and shout hooray because Preact Query comes with dedicated devtools! 🥳
7+
8+
When you begin your Preact Query journey, you'll want these devtools by your side. They help visualize all the inner workings of Preact Query and will likely save you hours of debugging if you find yourself in a pinch!
9+
10+
> For Chrome, Firefox, and Edge users: Third-party browser extensions are available for debugging TanStack Query directly in browser DevTools. These provide the same functionality as the framework-specific devtools packages:
11+
>
12+
> - <img alt="Chrome logo" src="https://www.google.com/chrome/static/images/chrome-logo.svg" width="16" height="16" class="inline mr-1 not-prose" /> [Devtools for Chrome](https://chromewebstore.google.com/detail/tanstack-query-devtools/annajfchloimdhceglpgglpeepfghfai)
13+
> - <img alt="Firefox logo" src="https://upload.wikimedia.org/wikipedia/commons/a/a0/Firefox_logo%2C_2019.svg" width="16" height="16" class="inline mr-1 not-prose" /> [Devtools for Firefox](https://addons.mozilla.org/en-US/firefox/addon/tanstack-query-devtools/)
14+
> - <img alt="Edge logo" src="https://upload.wikimedia.org/wikipedia/commons/9/98/Microsoft_Edge_logo_%282019%29.svg" width="16" height="16" class="inline mr-1 not-prose" /> [Devtools for Edge](https://microsoftedge.microsoft.com/addons/detail/tanstack-query-devtools/edmdpkgkacmjopodhfolmphdenmddobj)
15+
16+
> Note that since version 5, the dev tools support observing mutations as well.
17+
18+
## Install and Import the Devtools
19+
20+
The devtools are a separate package that you need to install:
21+
22+
```bash
23+
npm i @tanstack/preact-query-devtools
24+
```
25+
26+
or
27+
28+
```bash
29+
pnpm add @tanstack/preact-query-devtools
30+
```
31+
32+
or
33+
34+
```bash
35+
yarn add @tanstack/preact-query-devtools
36+
```
37+
38+
or
39+
40+
```bash
41+
bun add @tanstack/preact-query-devtools
42+
```
43+
44+
For Next 13+ App Dir you must install it as a dev dependency for it to work.
45+
46+
You can import the devtools like this:
47+
48+
```tsx
49+
import { PreactQueryDevtools } from '@tanstack/preact-query-devtools'
50+
```
51+
52+
By default, Preact Query Devtools are only included in bundles when `process.env.NODE_ENV === 'development'`, so you don't need to worry about excluding them during a production build.
53+
54+
## Floating Mode
55+
56+
Floating Mode will mount the devtools as a fixed, floating element in your app and provide a toggle in corner of the screen to show and hide the devtools. This toggle state will be stored and remembered in localStorage across reloads.
57+
58+
Place the following code as high in your Preact app as you can. The closer it is to the root of the page, the better it will work!
59+
60+
```tsx
61+
import { PreactQueryDevtools } from '@tanstack/preact-query-devtools'
62+
63+
function App() {
64+
return (
65+
<QueryClientProvider client={queryClient}>
66+
{/* The rest of your application */}
67+
<PreactQueryDevtools initialIsOpen={false} />
68+
</QueryClientProvider>
69+
)
70+
}
71+
```
72+
73+
### Options
74+
75+
- `initialIsOpen: boolean`
76+
- Set this `true` if you want the dev tools to default to being open
77+
- `buttonPosition?: "top-left" | "top-right" | "bottom-left" | "bottom-right" | "relative"`
78+
- Defaults to `bottom-right`
79+
- The position of the Preact Query logo to open and close the devtools panel
80+
- If `relative`, the button is placed in the location that you render the devtools.
81+
- `position?: "top" | "bottom" | "left" | "right"`
82+
- Defaults to `bottom`
83+
- The position of the Preact Query devtools panel
84+
- `client?: QueryClient`,
85+
- Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used.
86+
- `errorTypes?: { name: string; initializer: (query: Query) => TError}[]`
87+
- Use this to predefine some errors that can be triggered on your queries. Initializer will be called (with the specific query) when that error is toggled on from the UI. It must return an Error.
88+
- `styleNonce?: string`
89+
- Use this to pass a nonce to the style tag that is added to the document head. This is useful if you are using a Content Security Policy (CSP) nonce to allow inline styles.
90+
- `shadowDOMTarget?: ShadowRoot`
91+
- Default behavior will apply the devtool's styles to the head tag within the DOM.
92+
- Use this to pass a shadow DOM target to the devtools so that the styles will be applied within the shadow DOM instead of within head tag in the light DOM.
93+
94+
## Embedded Mode
95+
96+
Embedded mode will show the development tools as a fixed element in your application, so you can use our panel in your own development tools.
97+
98+
Place the following code as high in your Preact app as you can. The closer it is to the root of the page, the better it will work!
99+
100+
```tsx
101+
import { PreactQueryDevtoolsPanel } from '@tanstack/preact-query-devtools'
102+
103+
function App() {
104+
const [isOpen, setIsOpen] = useState(false)
105+
106+
return (
107+
<QueryClientProvider client={queryClient}>
108+
{/* The rest of your application */}
109+
<button
110+
onClick={() => setIsOpen(!isOpen)}
111+
>{`${isOpen ? 'Close' : 'Open'} the devtools panel`}</button>
112+
{isOpen && <PreactQueryDevtoolsPanel onClose={() => setIsOpen(false)} />}
113+
</QueryClientProvider>
114+
)
115+
}
116+
```
117+
118+
### Options
119+
120+
- `style?: JSX.CSSProperties`
121+
- Custom styles for the devtools panel
122+
- Default: `{ height: '500px' }`
123+
- Example: `{ height: '100%' }`
124+
- Example: `{ height: '100%', width: '100%' }`
125+
- `onClose?: () => unknown`
126+
- Callback function that is called when the devtools panel is closed
127+
- `client?: QueryClient`,
128+
- Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used.
129+
- `errorTypes?: { name: string; initializer: (query: Query) => TError}[]`
130+
- Use this to predefine some errors that can be triggered on your queries. Initializer will be called (with the specific query) when that error is toggled on from the UI. It must return an Error.
131+
- `styleNonce?: string`
132+
- Use this to pass a nonce to the style tag that is added to the document head. This is useful if you are using a Content Security Policy (CSP) nonce to allow inline styles.
133+
- `shadowDOMTarget?: ShadowRoot`
134+
- Default behavior will apply the devtool's styles to the head tag within the DOM.
135+
- Use this to pass a shadow DOM target to the devtools so that the styles will be applied within the shadow DOM instead of within head tag in the light DOM.
136+
137+
## Devtools in production
138+
139+
Devtools are excluded in production builds. However, it might be desirable to lazy load the devtools in production:
140+
141+
```tsx
142+
import { Suspense } from 'preact/compat'
143+
import { lazy } from 'preact/iso'
144+
import { QueryClient, QueryClientProvider } from '@tanstack/preact-query'
145+
import { PreactQueryDevtools } from '@tanstack/preact-query-devtools'
146+
import { Example } from './Example'
147+
148+
const queryClient = new QueryClient()
149+
150+
const PreactQueryDevtoolsProduction = lazy(() =>
151+
import('@tanstack/preact-query-devtools/build/modern/production.js').then(
152+
(d) => ({
153+
default: d.PreactQueryDevtools,
154+
}),
155+
),
156+
)
157+
158+
function App() {
159+
const [showDevtools, setShowDevtools] = useState(false)
160+
161+
useEffect(() => {
162+
// @ts-expect-error
163+
window.toggleDevtools = () => setShowDevtools((old) => !old)
164+
}, [])
165+
166+
return (
167+
<QueryClientProvider client={queryClient}>
168+
<Example />
169+
<PreactQueryDevtools initialIsOpen />
170+
{showDevtools && (
171+
<Suspense fallback={null}>
172+
<PreactQueryDevtoolsProduction />
173+
</Suspense>
174+
)}
175+
</QueryClientProvider>
176+
)
177+
}
178+
179+
export default App
180+
```
181+
182+
With this, calling `window.toggleDevtools()` will download the devtools bundle and show them.
183+
184+
### Modern bundlers
185+
186+
If your bundler supports package exports, you can use the following import path:
187+
188+
```tsx
189+
const PreactQueryDevtoolsProduction = lazy(() =>
190+
import('@tanstack/preact-query-devtools/production').then((d) => ({
191+
default: d.PreactQueryDevtools,
192+
})),
193+
)
194+
```
195+
196+
For TypeScript, you would need to set `moduleResolution: 'nodenext'` in your tsconfig, which requires at least TypeScript v4.7.

docs/framework/preact/graphql.md

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
---
2+
id: graphql
3+
title: GraphQL
4+
---
5+
6+
Because Preact Query's fetching mechanisms are agnostically built on Promises, you can use Preact Query with literally any asynchronous data fetching client, including GraphQL!
7+
8+
> Keep in mind that Preact Query does not support normalized caching. While a vast majority of users do not actually need a normalized cache or even benefit from it as much as they believe they do, there may be very rare circumstances that may warrant it so be sure to check with us first to make sure it's truly something you need!
9+
10+
[//]: # 'Codegen'
11+
12+
## Type-Safety and Code Generation
13+
14+
Preact Query, used in combination with `graphql-request^5` and [GraphQL Code Generator](https://graphql-code-generator.com/) provides full-typed GraphQL operations:
15+
16+
```tsx
17+
import request from 'graphql-request'
18+
import { useQuery } from '@tanstack/preact-query'
19+
20+
import { graphql } from './gql/gql'
21+
22+
const allFilmsWithVariablesQueryDocument = graphql(/* GraphQL */ `
23+
query allFilmsWithVariablesQuery($first: Int!) {
24+
allFilms(first: $first) {
25+
edges {
26+
node {
27+
id
28+
title
29+
}
30+
}
31+
}
32+
}
33+
`)
34+
35+
function App() {
36+
// `data` is fully typed!
37+
const { data } = useQuery({
38+
queryKey: ['films'],
39+
queryFn: async () =>
40+
request(
41+
'https://swapi-graphql.netlify.app/.netlify/functions/index',
42+
allFilmsWithVariablesQueryDocument,
43+
// variables are type-checked too!
44+
{ first: 10 },
45+
),
46+
})
47+
// ...
48+
}
49+
```
50+
51+
_You can find a [complete example in the repo](https://github.com/dotansimha/graphql-code-generator/tree/7c25c4eeb77f88677fd79da557b7b5326e3f3950/examples/front-end/react/tanstack-react-query)_
52+
53+
Get started with the [dedicated guide on GraphQL Code Generator documentation](https://www.the-guild.dev/graphql/codegen/docs/guides/react-vue).
54+
55+
[//]: # 'Codegen'
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
---
2+
id: background-fetching-indicators
3+
title: Background Fetching Indicators
4+
---
5+
6+
A query's `status === 'pending'` state is sufficient enough to show the initial hard-loading state for a query, but sometimes you may want to display an additional indicator that a query is refetching in the background. To do this, queries also supply you with an `isFetching` boolean that you can use to show that it's in a fetching state, regardless of the state of the `status` variable:
7+
8+
[//]: # 'Example'
9+
10+
```tsx
11+
function Todos() {
12+
const {
13+
status,
14+
data: todos,
15+
error,
16+
isFetching,
17+
} = useQuery({
18+
queryKey: ['todos'],
19+
queryFn: fetchTodos,
20+
})
21+
22+
return status === 'pending' ? (
23+
<span>Loading...</span>
24+
) : status === 'error' ? (
25+
<span>Error: {error.message}</span>
26+
) : (
27+
<>
28+
{isFetching ? <div>Refreshing...</div> : null}
29+
30+
<div>
31+
{todos.map((todo) => (
32+
<Todo todo={todo} />
33+
))}
34+
</div>
35+
</>
36+
)
37+
}
38+
```
39+
40+
[//]: # 'Example'
41+
42+
## Displaying Global Background Fetching Loading State
43+
44+
In addition to individual query loading states, if you would like to show a global loading indicator when **any** queries are fetching (including in the background), you can use the `useIsFetching` hook:
45+
46+
[//]: # 'Example2'
47+
48+
```tsx
49+
import { useIsFetching } from '@tanstack/preact-query'
50+
51+
function GlobalLoadingIndicator() {
52+
const isFetching = useIsFetching()
53+
54+
return isFetching ? (
55+
<div>Queries are fetching in the background...</div>
56+
) : null
57+
}
58+
```
59+
60+
[//]: # 'Example2'
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
---
2+
id: caching
3+
title: Caching Examples
4+
---
5+
6+
> Please thoroughly read the [Important Defaults](./important-defaults.md) before reading this guide
7+
8+
## Basic Example
9+
10+
This caching example illustrates the story and lifecycle of:
11+
12+
- Query Instances with and without cache data
13+
- Background Refetching
14+
- Inactive Queries
15+
- Garbage Collection
16+
17+
Let's assume we are using the default `gcTime` of **5 minutes** and the default `staleTime` of `0`.
18+
19+
- A new instance of `useQuery({ queryKey: ['todos'], queryFn: fetchTodos })` mounts.
20+
- Since no other queries have been made with the `['todos']` query key, this query will show a hard loading state and make a network request to fetch the data.
21+
- When the network request has completed, the returned data will be cached under the `['todos']` key.
22+
- The hook will mark the data as stale after the configured `staleTime` (defaults to `0`, or immediately).
23+
- A second instance of `useQuery({ queryKey: ['todos'], queryFn: fetchTodos })` mounts elsewhere.
24+
- Since the cache already has data for the `['todos']` key from the first query, that data is immediately returned from the cache.
25+
- The new instance triggers a new network request using its query function.
26+
- Note that regardless of whether both `fetchTodos` query functions are identical or not, both queries' [`status`](../reference/useQuery.md) are updated (including `isFetching`, `isPending`, and other related values) because they have the same query key.
27+
- When the request completes successfully, the cache's data under the `['todos']` key is updated with the new data, and both instances are updated with the new data.
28+
- Both instances of the `useQuery({ queryKey: ['todos'], queryFn: fetchTodos })` query are unmounted and no longer in use.
29+
- Since there are no more active instances of this query, a garbage collection timeout is set using `gcTime` to delete and garbage collect the query (defaults to **5 minutes**).
30+
- Before the cache timeout (gcTime) has completed, another instance of `useQuery({ queryKey: ['todos'], queryFn: fetchTodos })` mounts. The query immediately returns the available cached data while the `fetchTodos` function is being run in the background. When it completes successfully, it will populate the cache with fresh data.
31+
- The final instance of `useQuery({ queryKey: ['todos'], queryFn: fetchTodos })` unmounts.
32+
- No more instances of `useQuery({ queryKey: ['todos'], queryFn: fetchTodos })` appear within **5 minutes**.
33+
- The cached data under the `['todos']` key is deleted and garbage collected.

0 commit comments

Comments
 (0)