Skip to content

Commit

Permalink
fix: avoid reverting state to a fetching one (#5997)
Browse files Browse the repository at this point in the history
* fix: avoid reverting state to a fetching one

* Update packages/query-core/src/tests/query.test.tsx

---------

Co-authored-by: Dominik Dorfmeister <[email protected]>
  • Loading branch information
Andarist and TkDodo authored Sep 13, 2023
1 parent 4d859e9 commit 88a8b30
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
2 changes: 1 addition & 1 deletion packages/query-core/src/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -559,7 +559,7 @@ export class Query<
const error = action.error as unknown

if (isCancelledError(error) && error.revert && this.revertState) {
return { ...this.revertState }
return { ...this.revertState, fetchStatus: 'idle' }
}

return {
Expand Down
52 changes: 52 additions & 0 deletions packages/query-core/src/tests/query.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -911,4 +911,56 @@ describe('query', () => {

unsubscribe()
})

test('should always revert to idle state (#5958)', async () => {
let mockedData = [1]

const key = queryKey()

const queryFn = jest.fn<
Promise<unknown>,
[QueryFunctionContext<ReturnType<typeof queryKey>>]
>()

queryFn.mockImplementation(({ signal }) => {
return new Promise((resolve, reject) => {
const abortListener = () => {
clearTimeout(timerId)
reject(signal!.reason)
}
signal!.addEventListener('abort', abortListener)

const timerId = setTimeout(() => {
signal!.removeEventListener('abort', abortListener)
resolve(mockedData.join(' - '))
}, 50)
})
})

const observer = new QueryObserver(queryClient, {
queryKey: key,
queryFn,
})
const unsubscribe = observer.subscribe(() => undefined)
await sleep(60) // let it resolve

mockedData = [1, 2] // update "server" state in the background

queryClient.invalidateQueries(key)
await sleep(1)
queryClient.invalidateQueries(key)
await sleep(1)
unsubscribe() // unsubscribe to simulate unmount

// set up a new observer to simulate a mount of new component
const newObserver = new QueryObserver(queryClient, {
queryKey: key,
queryFn,
})

const spy = jest.fn()
newObserver.subscribe(({ data }) => spy(data))
await sleep(60) // let it resolve
expect(spy).toHaveBeenCalledWith('1 - 2')
})
})

0 comments on commit 88a8b30

Please sign in to comment.