Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/remove idle state #3302

Merged
merged 4 commits into from
Feb 24, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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>
)
}
```
4 changes: 2 additions & 2 deletions 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 Expand Up @@ -41,6 +41,6 @@ The [React Query Devtools](../devtools) will show Queries in a `paused` state if

## Signature

- `networkMode: 'online' | 'always' | 'offlineFirst`
- `networkMode: 'online' | 'always' | 'offlineFirst'`
- optional
- defaults to `'online'`
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
2 changes: 1 addition & 1 deletion src/core/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -618,7 +618,7 @@ function getDefaultState<
fetchFailureCount: 0,
fetchMeta: null,
isInvalidated: false,
status: hasData ? 'success' : 'idle',
status: hasData ? 'success' : 'loading',
fetchStatus: 'idle',
}
}
3 changes: 1 addition & 2 deletions src/core/queryObserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -489,7 +489,7 @@ export class QueryObserver<
if (
typeof options.placeholderData !== 'undefined' &&
typeof data === 'undefined' &&
(status === 'loading' || status === 'idle')
status === 'loading'
) {
let placeholderData

Expand Down Expand Up @@ -541,7 +541,6 @@ export class QueryObserver<
isLoading: status === 'loading',
isSuccess: status === 'success',
isError: status === 'error',
isIdle: status === 'idle',
data,
dataUpdatedAt,
error,
Expand Down
56 changes: 28 additions & 28 deletions src/core/tests/queriesObserver.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -88,20 +88,20 @@ describe('queriesObserver', () => {
unsubscribe()
expect(results.length).toBe(6)
expect(results[0]).toMatchObject([
{ status: 'idle', data: undefined },
{ status: 'idle', data: undefined },
{ status: 'loading', fetchStatus: 'idle', data: undefined },
{ status: 'loading', fetchStatus: 'idle', data: undefined },
])
expect(results[1]).toMatchObject([
{ status: 'loading', data: undefined },
{ status: 'idle', data: undefined },
{ status: 'loading', fetchStatus: 'fetching', data: undefined },
{ status: 'loading', fetchStatus: 'idle', data: undefined },
])
expect(results[2]).toMatchObject([
{ status: 'loading', data: undefined },
{ status: 'loading', data: undefined },
{ status: 'loading', fetchStatus: 'fetching', data: undefined },
{ status: 'loading', fetchStatus: 'fetching', data: undefined },
])
expect(results[3]).toMatchObject([
{ status: 'success', data: 1 },
{ status: 'loading', data: undefined },
{ status: 'loading', fetchStatus: 'fetching', data: undefined },
])
expect(results[4]).toMatchObject([
{ status: 'success', data: 1 },
Expand Down Expand Up @@ -138,20 +138,20 @@ describe('queriesObserver', () => {
expect(queryCache.find(key2, { type: 'active' })).toBeUndefined()
expect(results.length).toBe(6)
expect(results[0]).toMatchObject([
{ status: 'idle', data: undefined },
{ status: 'idle', data: undefined },
{ status: 'loading', fetchStatus: 'idle', data: undefined },
{ status: 'loading', fetchStatus: 'idle', data: undefined },
])
expect(results[1]).toMatchObject([
{ status: 'loading', data: undefined },
{ status: 'idle', data: undefined },
{ status: 'loading', fetchStatus: 'fetching', data: undefined },
{ status: 'loading', fetchStatus: 'idle', data: undefined },
])
expect(results[2]).toMatchObject([
{ status: 'loading', data: undefined },
{ status: 'loading', data: undefined },
{ status: 'loading', fetchStatus: 'fetching', data: undefined },
{ status: 'loading', fetchStatus: 'fetching', data: undefined },
])
expect(results[3]).toMatchObject([
{ status: 'success', data: 1 },
{ status: 'loading', data: undefined },
{ status: 'loading', fetchStatus: 'fetching', data: undefined },
])
expect(results[4]).toMatchObject([
{ status: 'success', data: 1 },
Expand Down Expand Up @@ -183,20 +183,20 @@ describe('queriesObserver', () => {
unsubscribe()
expect(results.length).toBe(6)
expect(results[0]).toMatchObject([
{ status: 'idle', data: undefined },
{ status: 'idle', data: undefined },
{ status: 'loading', fetchStatus: 'idle', data: undefined },
{ status: 'loading', fetchStatus: 'idle', data: undefined },
])
expect(results[1]).toMatchObject([
{ status: 'loading', data: undefined },
{ status: 'idle', data: undefined },
{ status: 'loading', fetchStatus: 'fetching', data: undefined },
{ status: 'loading', fetchStatus: 'idle', data: undefined },
])
expect(results[2]).toMatchObject([
{ status: 'loading', data: undefined },
{ status: 'loading', data: undefined },
{ status: 'loading', fetchStatus: 'fetching', data: undefined },
{ status: 'loading', fetchStatus: 'fetching', data: undefined },
])
expect(results[3]).toMatchObject([
{ status: 'success', data: 1 },
{ status: 'loading', data: undefined },
{ status: 'loading', fetchStatus: 'fetching', data: undefined },
])
expect(results[4]).toMatchObject([
{ status: 'success', data: 1 },
Expand Down Expand Up @@ -231,20 +231,20 @@ describe('queriesObserver', () => {
unsubscribe()
expect(results.length).toBe(5)
expect(results[0]).toMatchObject([
{ status: 'idle', data: undefined },
{ status: 'idle', data: undefined },
{ status: 'loading', fetchStatus: 'idle', data: undefined },
{ status: 'loading', fetchStatus: 'idle', data: undefined },
])
expect(results[1]).toMatchObject([
{ status: 'loading', data: undefined },
{ status: 'idle', data: undefined },
{ status: 'loading', fetchStatus: 'fetching', data: undefined },
{ status: 'loading', fetchStatus: 'idle', data: undefined },
])
expect(results[2]).toMatchObject([
{ status: 'loading', data: undefined },
{ status: 'loading', data: undefined },
{ status: 'loading', fetchStatus: 'fetching', data: undefined },
{ status: 'loading', fetchStatus: 'fetching', data: undefined },
])
expect(results[3]).toMatchObject([
{ status: 'success', data: 1 },
{ status: 'loading', data: undefined },
{ status: 'loading', fetchStatus: 'fetching', data: undefined },
])
expect(results[4]).toMatchObject([
{ status: 'success', data: 1 },
Expand Down
6 changes: 4 additions & 2 deletions src/core/tests/query.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -264,12 +264,14 @@ describe('query', () => {
if (typeof AbortSignal === 'function') {
expect(query.state).toMatchObject({
data: undefined,
status: 'idle',
status: 'loading',
fetchStatus: 'idle',
})
} else {
expect(query.state).toMatchObject({
data: 'data',
status: 'success',
fetchStatus: 'idle',
dataUpdateCount: 1,
})
}
Expand Down Expand Up @@ -390,7 +392,7 @@ describe('query', () => {
// The query should
expect(queryFn).toHaveBeenCalledTimes(1) // have been called,
expect(query.state.error).toBe(null) // not have an error, and
expect(query.state.status).toBe('idle') // not be loading any longer
expect(query.state.fetchStatus).toBe('idle') // not be loading any longer
})

test('should be able to refetch a cancelled query', async () => {
Expand Down
Loading