Skip to content

fix: make sure setQueryData is not considered as initial data #966

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

Merged
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
2 changes: 1 addition & 1 deletion docs/src/pages/docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ const queryInfo = useQuery({
- A function like `attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)` applies exponential backoff.
- A function like `attempt => attempt * 1000` applies linear backoff.
- `staleTime: Int | Infinity`
- The time in milliseconds that cache data remains fresh. After a successful cache update, that cache data will become stale after this duration.
- The time in milliseconds after data is considered stale.
- If set to `Infinity`, query will never go stale
- `cacheTime: Int | Infinity`
- The time in milliseconds that unused/inactive cache data remains in memory. When a query's cache becomes unused or inactive, that cache data will be garbage collected after this duration.
Expand Down
4 changes: 2 additions & 2 deletions src/core/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -591,11 +591,11 @@ function getDefaultState<TResult, TError>(
return {
...getStatusProps(initialStatus),
error: null,
isFetched: false,
isFetched: Boolean(config.initialFetched),
isFetching: initialStatus === QueryStatus.Loading,
isFetchingMore: false,
failureCount: 0,
fetchedCount: 0,
fetchedCount: config.initialFetched ? 1 : 0,
data: initialData,
updatedAt: Date.now(),
canFetchMore: hasMorePages(config, initialData),
Expand Down
2 changes: 1 addition & 1 deletion src/core/queryCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,7 @@ export class QueryCache {
}

this.buildQuery<TResult, TError>(queryKey, {
initialStale: typeof config?.staleTime === 'undefined',
initialFetched: true,
initialData: functionalUpdate(updater, undefined),
...config,
})
Expand Down
4 changes: 2 additions & 2 deletions src/core/queryObserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ export class QueryObserver<TResult, TError> {
}

const timeElapsed = Date.now() - updatedAt
const timeUntilStale = staleTime - timeElapsed
const timeUntilStale = staleTime - timeElapsed + 1
const timeout = Math.max(timeUntilStale, 0)

this.staleTimeoutId = setTimeout(() => {
Expand Down Expand Up @@ -244,7 +244,7 @@ export class QueryObserver<TResult, TError> {
isPreviousData = true
}

let isStale = false
let isStale

// When the query has not been fetched yet and this is the initial render,
// determine the staleness based on the initialStale or existence of initial data.
Expand Down
14 changes: 12 additions & 2 deletions src/core/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,14 @@ export interface BaseQueryConfig<TResult, TError = unknown, TData = TResult> {
*/
retry?: boolean | number | ((failureCount: number, error: TError) => boolean)
retryDelay?: number | ((retryAttempt: number) => number)
staleTime?: number
cacheTime?: number
isDataEqual?: (oldData: unknown, newData: unknown) => boolean
queryFn?: QueryFunction<TData>
queryKey?: QueryKey
queryKeySerializerFn?: QueryKeySerializerFunction
queryFnParamsFilter?: (args: ArrayQueryKey) => ArrayQueryKey
initialData?: TResult | InitialDataFunction<TResult>
initialStale?: boolean | InitialStaleFunction
initialFetched?: boolean
infinite?: true
/**
* Set this to `false` to disable structural sharing between query results.
Expand All @@ -75,6 +74,17 @@ export interface QueryObserverConfig<
* Defaults to `true`.
*/
enabled?: boolean | unknown
/**
* The time in milliseconds after data is considered stale.
* If set to `Infinity`, the data will never be stale.
*/
staleTime?: number
/**
* If set, this will mark any `initialData` provided as stale and will likely cause it to be refetched on mount.
* If a function is passed, it will be called only when appropriate to resolve the `initialStale` value.
* This can be useful if your `initialStale` value is costly to calculate.
*/
initialStale?: boolean | InitialStaleFunction
/**
* If set to a number, the query will continuously refetch at this frequency in milliseconds.
* Defaults to `false`.
Expand Down
6 changes: 2 additions & 4 deletions src/hydration/hydration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,10 +83,8 @@ export function hydrate<TResult>(

for (const dehydratedQuery of queries) {
const queryKey = dehydratedQuery.config.queryKey
const queryConfig: QueryConfig<TResult> = dehydratedQuery.config as QueryConfig<
TResult
>

const queryConfig = dehydratedQuery.config as QueryConfig<TResult>
queryConfig.initialFetched = true
const query = queryCache.buildQuery(queryKey, queryConfig)
query.state.updatedAt = dehydratedQuery.updatedAt
}
Expand Down
48 changes: 44 additions & 4 deletions src/react/tests/useQuery.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1225,6 +1225,41 @@ describe('useQuery', () => {
consoleMock.mockRestore()
})

it('should fetch on mount when a query was already created with setQueryData', async () => {
const key = queryKey()
const states: QueryResult<string>[] = []

queryCache.setQueryData(key, 'prefetched')

function Page() {
const state = useQuery(key, () => 'data')
states.push(state)
return null
}

render(<Page />)

await waitFor(() =>
expect(states).toMatchObject([
{
data: 'prefetched',
isFetching: false,
isStale: true,
},
{
data: 'prefetched',
isFetching: true,
isStale: true,
},
{
data: 'data',
isFetching: false,
isStale: true,
},
])
)
})

it('should refetch after focus regain', async () => {
const key = queryKey()
const states: QueryResult<string>[] = []
Expand All @@ -1245,29 +1280,34 @@ describe('useQuery', () => {

render(<Page />)

await waitFor(() => expect(states.length).toBe(2))
await waitFor(() => expect(states.length).toBe(3))

act(() => {
// reset visibilityState to original value
mockVisibilityState(originalVisibilityState)
window.dispatchEvent(new FocusEvent('focus'))
})

await waitFor(() => expect(states.length).toBe(4))
await waitFor(() => expect(states.length).toBe(5))

expect(states).toMatchObject([
{
data: 'prefetched',
isFetching: false,
isStale: false,
isStale: true,
},
{
data: 'prefetched',
isFetching: true,
isStale: true,
},
{
data: 'data',
isFetching: false,
isStale: true,
},
{
data: 'prefetched',
data: 'data',
isFetching: true,
isStale: true,
},
Expand Down