Skip to content

Commit

Permalink
feat: remove idle state
Browse files Browse the repository at this point in the history
documentation around the removed idle state and the new fetchingStatus
  • Loading branch information
TkDodo committed Feb 16, 2022
1 parent 87e531b commit f8e32fa
Show file tree
Hide file tree
Showing 5 changed files with 96 additions and 28 deletions.
24 changes: 21 additions & 3 deletions docs/src/pages/guides/dependent-queries.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,33 @@ const { data: user } = useQuery(['user', email], getUserByEmail)
const userId = user?.id

// Then get the user's projects
const { isIdle, data: projects } = useQuery(
const { status, fetchStatus, data: projects } = useQuery(
['projects', userId],
getProjectsByUser,
{
// The query will not execute until the userId exists
enabled: !!userId,
}
)
```
The `projects` query will start in:
```js
status: 'loading'
fetchStatus: 'idle'
```

As soon as the `user` is available, the `projects` query will be `enabled` and will then transition to:

// isIdle will be `true` until `enabled` is true and the query begins to fetch.
// It will then go to the `isLoading` stage and hopefully the `isSuccess` stage :)
```js
status: 'loading'
fetchStatus: 'fetching'
```

Once we have the projects, it will go to:

```js
status: 'success'
fetchStatus: 'idle'
```
65 changes: 49 additions & 16 deletions docs/src/pages/guides/disabling-queries.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,47 +10,80 @@ When `enabled` is `false`:
- If the query has cached data
- The query will be initialized in the `status === 'success'` or `isSuccess` state.
- If the query does not have cached data
- The query will start in the `status === 'idle'` or `isIdle` state.
- The query will start in the `status === 'loading'` and `fetchStatus === 'idle'`
- The query will not automatically fetch on mount.
- The query will not automatically refetch in the background when new instances mount or new instances appearing
- The query will not automatically refetch in the background
- The query will ignore query client `invalidateQueries` and `refetchQueries` calls that would normally result in the query refetching.
- `refetch` can be used to manually trigger the query to fetch.
- `refetch` returned from `useQuery` can be used to manually trigger the query to fetch.

```js
```jsx
function Todos() {
const {
isIdle,
isLoading,
isError,
data,
error,
refetch,
isFetching,
isFetching
} = useQuery(['todos'], fetchTodoList, {
enabled: false,
})

return (
<>
<div>
<button onClick={() => refetch()}>Fetch Todos</button>

{isIdle ? (
'Not ready...'
) : isLoading ? (
<span>Loading...</span>
) : isError ? (
<span>Error: {error.message}</span>
) : (
{data ? (
<>
<ul>
{data.map(todo => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
<div>{isFetching ? 'Fetching...' : null}</div>
</>
) : (
isError ? (
<span>Error: {error.message}</span>
) : (
(isLoading && !isFetching) ? (
<span>Not ready ...</span>
) : (
<span>Loading...</span>
)
)
)}
</>

<div>{isFetching ? 'Fetching...' : null}</div>
</div>
)
}
```

Permanently disabling a query opts out of many great features that react-query has to offer (like background refetches), and it's also not the idiomatic way. It takes you from the declartive 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:

## Lazy Queries

The enabled option can not only be used to permenantly 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:

```jsx
function Todos() {
const [filter, setFilter] = React.useState('')

const { data } = useQuery(
['todos', filter],
() => fetchTodos(filter),
{
// ⬇️ disabled as long as the filter is empty
enabled: !!filter
}
)

return (
<div>
// 🚀 applying the filter will enable and execute the query
<FiltersForm onApply={setFilter} />
{data && <TodosTable data={data}} />
</div>
)
}
```
2 changes: 1 addition & 1 deletion docs/src/pages/guides/network-mode.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ Since React Query is most often used for data fetching in combination with data

## Network Mode: online

In this mode, Queries and Mutations will not fire unless you have network connection. This is the default mode. If a fetch is initiated for a query, it will always stay in the `state` (`loading`, `idle`, `error`, `success`) it is in if the fetch cannot be made because there is no network connection. However, a `fetchStatus` is exposed additionally. This can be either:
In this mode, Queries and Mutations will not fire unless you have network connection. This is the default mode. If a fetch is initiated for a query, it will always stay in the `state` (`loading`, `error`, `success`) it is in if the fetch cannot be made because there is no network connection. However, a [fetchStatus](./queries#fetchstatus) is exposed additionally. This can be either:

- `fetching`: The `queryFn` is really executing - a request is in-flight.
- `paused`: The query is not executing - it is `paused` until you have connection again
Expand Down
26 changes: 23 additions & 3 deletions docs/src/pages/guides/queries.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,16 +32,14 @@ const result = useQuery(['todos'], fetchTodoList)

The `result` object contains a few very important states you'll need to be aware of to be productive. A query can only be in one of the following states at any given moment:

- `isLoading` or `status === 'loading'` - The query has no data and is currently fetching
- `isLoading` or `status === 'loading'` - The query has no data yet
- `isError` or `status === 'error'` - The query encountered an error
- `isSuccess` or `status === 'success'` - The query was successful and data is available
- `isIdle` or `status === 'idle'` - The query is currently disabled (you'll learn more about this in a bit)

Beyond those primary states, more information is available depending on the state of the query:

- `error` - If the query is in an `isError` state, the error is available via the `error` property.
- `data` - If the query is in a `success` state, the data is available via the `data` property.
- `isFetching` - In any state, if the query is fetching at any time (including background refetching) `isFetching` will be `true`.

For **most** queries, it's usually sufficient to check for the `isLoading` state, then the `isError` state, then finally, assume that the data is available and render the successful state:

Expand Down Expand Up @@ -92,6 +90,28 @@ function Todos() {
)
}
```

TypeScript will also narrow the type of `data` correctly if you've checked for `loading` and `error` before accessing it.

### FetchStatus

In addition to the `status` field, the `result` object, you will also get an additional `fetchStatus`property with the following options:

- `fetchStatus === 'fetching'` - The query is currently fetching.
- `fetchStatus === 'paused'` - The query wanted to fetch, but it is paused. Read more about this in the [Network Mode](./network-mode) guide.
- `fetchStatus === 'idle'` - The query is not doing anything at the moment.

### Why two different states?

Background refetches and stale-while-revalidate logic make all combinations for `status` and `fetchStatus` possible. For example:
- a query in `success` status will usually be in `idle` fetchStatus, but it could also be in `fetching` if a background refetch is happening.
- a query that mounts and has no data will usually be in `loading` status and `fetching` fetchStatus, but it could also be `paused` if there is no network connection.

So keep in mind that a query can be in `loading` state without actually fetching data. As a rule of thumb:

- The `status` gives information about the `data`: Do we have any or not?
- The `fetchStatus` gives information about the `queryFn`: Is it running or not?

## Further Reading

For an alternative way of performing status checks, have a look at the [Community Resources](../community/tkdodos-blog#4-status-checks-in-react-query).
7 changes: 2 additions & 5 deletions docs/src/pages/reference/useQuery.md
Original file line number Diff line number Diff line change
Expand Up @@ -190,12 +190,9 @@ const result = useQuery({

- `status: String`
- Will be:
- `idle` if the query is idle. This only happens if a query is initialized with `enabled: false` and no initial data is available.
- `loading` if the query is in a "hard" loading state. This means there is no cached data and the query is currently fetching, eg `isFetching === true`
- `error` if the query attempt resulted in an error. The corresponding `error` property has the error received from the attempted fetch
- `success` if the query has received a response with no errors and is ready to display its data. The corresponding `data` property on the query is the data received from the successful fetch or if the query's `enabled` property is set to `false` and has not been fetched yet `data` is the first `initialData` supplied to the query on initialization.
- `isIdle: boolean`
- A derived boolean from the `status` variable above, provided for convenience.
- `isLoading: boolean`
- A derived boolean from the `status` variable above, provided for convenience.
- `isSuccess: boolean`
Expand Down Expand Up @@ -229,8 +226,8 @@ const result = useQuery({
- This property can be used to not show any previously cached data.
- `fetchStatus: FetchStatus`
- `fetching`: Is `true` whenever the queryFn is executing, which includes initial `loading` as well as background refetches.
- `paused`: The query wanted to fetch, but has been `paused`
- `idle`: The query is not fetching
- `paused`: The query wanted to fetch, but has been `paused`.
- `idle`: The query is not fetching.
- see [Network Mode](../guides/network-mode) for more information.
- `isFetching: boolean`
- A derived boolean from the `fetchStatus` variable above, provided for convenience.
Expand Down

0 comments on commit f8e32fa

Please sign in to comment.