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

disabling-queries.md

128 lines4.4 KB

1---
2id: disabling-queries
3title: Disabling/Pausing Queries
4---
5​
6If you ever want to disable a query from automatically running, you can use the `enabled = false` option. The enabled option also accepts a callback that returns a boolean.
7​
8When `enabled` is `false`:
9​
10- If the query has cached data, then the query will be initialized in the `status === 'success'` or `isSuccess` state.
11- If the query does not have cached data, then the query will start in the `status === 'pending'` and `fetchStatus === 'idle'` state.
12- The query will not automatically fetch on mount.
13- The query will not automatically refetch in the background.
14- The query will ignore query client `invalidateQueries` and `refetchQueries` calls that would normally result in the query refetching.
15- `refetch` returned from `useQuery` can be used to manually trigger the query to fetch. However, it will not work with `skipToken`.
16​
17> TypeScript users may prefer to use [skipToken](#typesafe-disabling-of-queries-using-skiptoken) as an alternative to `enabled = false`.
18​
19[//]: # 'Example'
20​
21```tsx
22function Todos() {
23 const { isLoading, isError, data, error, refetch, isFetching } = useQuery({
24 queryKey: ['todos'],
25 queryFn: fetchTodoList,
26 enabled: false,
27 })
28​
29 return (
30 <div>
31 <button onClick={() => refetch()}>Fetch Todos</button>
32​
33 {data ? (
34 <>
35 <ul>
36 {data.map((todo) => (
37 <li key={todo.id}>{todo.title}</li>
38 ))}
39 </ul>
40 </>
41 ) : isError ? (
42 <span>Error: {error.message}</span>
43 ) : isLoading ? (
44 <span>Loading...</span>
45 ) : (
46 <span>Not ready ...</span>
47 )}
48​
49 <div>{isFetching ? 'Fetching...' : null}</div>
50 </div>
51 )
53```
54​
55[//]: # 'Example'
56​
57Permanently disabling a query opts out of many great features that TanStack Query has to offer (like background refetches), and it's also not the idiomatic way. It takes you from the declarative approach (defining dependencies when your query should run) into an imperative mode (fetch whenever I click here). It is also not possible to pass parameters to `refetch`. Oftentimes, all you want is a lazy query that defers the initial fetch:
58​
59## Lazy Queries
60​
61The enabled option can not only be used to permanently disable a query, but also to enable / disable it at a later time. A good example would be a filter form where you only want to fire off the first request once the user has entered a filter value:
62​
63[//]: # 'Example2'
64​
65```tsx
66function Todos() {
67 const [filter, setFilter] = React.useState('')
68​
69 const { data } = useQuery({
70 queryKey: ['todos', filter],
71 queryFn: () => fetchTodos(filter),
72 // ⬇️ disabled as long as the filter is empty
73 enabled: !!filter,
74 })
75​
76 return (
77 <div>
78 // πŸš€ applying the filter will enable and execute the query
79 <FiltersForm onApply={setFilter} />
80 {data && <TodosTable data={data} />}
81 </div>
82 )
84```
85​
86[//]: # 'Example2'
87​
88### isLoading (Previously: `isInitialLoading`)
89​
90Lazy queries will be in `status: 'pending'` right from the start because `pending` means that there is no data yet. This is technically true, however, since we are not currently fetching any data (as the query is not _enabled_), it also means you likely cannot use this flag to show a loading spinner.
91​
92If you are using disabled or lazy queries, you can use the `isLoading` flag instead. It's a derived flag that is computed from:
93​
94`isPending && isFetching`
95​
96so it will only be true if the query is currently fetching for the first time.
97​
98## Typesafe disabling of queries using `skipToken`
99​
100If you are using TypeScript, you can use the `skipToken` to disable a query. This is useful when you want to disable a query based on a condition, but you still want to keep the query to be type safe.
101​
102> IMPORTANT: `refetch` from `useQuery` will not work with `skipToken`. Other than that, `skipToken` works the same as `enabled: false`.
103​
104[//]: # 'Example3'
105​
106```tsx
107import { skipToken, useQuery } from '@tanstack/react-query'
108​
109function Todos() {
110 const [filter, setFilter] = React.useState<string | undefined>()
111​
112 const { data } = useQuery({
113 queryKey: ['todos', filter],
114 // ⬇️ disabled as long as the filter is undefined or empty
115 queryFn: filter ? () => fetchTodos(filter) : skipToken,
116 })
117​
118 return (
119 <div>
120 // πŸš€ applying the filter will enable and execute the query
121 <FiltersForm onApply={setFilter} />
122 {data && <TodosTable data={data} />}
123 </div>
124 )
126```
127​
128[//]: # 'Example3'