Skip to content

Commit 5d77624

Browse files
authored
Merge pull request #4364 from smacpherson64/master
2 parents 5ec40d8 + e5a9962 commit 5d77624

File tree

2 files changed

+52
-1
lines changed

2 files changed

+52
-1
lines changed

packages/toolkit/src/query/react/buildHooks.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -690,7 +690,7 @@ export function buildHooks<Definitions extends EndpointDefinitions>({
690690
// isFetching = true any time a request is in flight
691691
const isFetching = currentState.isLoading
692692
// isLoading = true only when loading while no data is present yet (initial load with no data in the cache)
693-
const isLoading = !hasData && isFetching
693+
const isLoading = (!lastResult || lastResult.isLoading || lastResult.isUninitialized) && !hasData && isFetching
694694
// isSuccess = true when data is present
695695
const isSuccess = currentState.isSuccess || (isFetching && hasData)
696696

packages/toolkit/src/query/tests/buildHooks.test.tsx

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -907,6 +907,57 @@ describe('hooks tests', () => {
907907
}
908908
})
909909

910+
test('Hook subscription failures do not reset isLoading state', async () => {
911+
const states: boolean[] = []
912+
913+
function Parent() {
914+
const { isLoading } = api.endpoints.getUserAndForceError.useQuery(1)
915+
916+
// Collect loading states to verify that it does not revert back to true.
917+
states.push(isLoading)
918+
919+
// Parent conditionally renders child when loading.
920+
if (isLoading) return null
921+
922+
return <Child />
923+
}
924+
925+
function Child() {
926+
// Using the same args as the parent
927+
api.endpoints.getUserAndForceError.useQuery(1)
928+
929+
return null
930+
}
931+
932+
render(<Parent />, { wrapper: storeRef.wrapper })
933+
934+
// Allow at least three state effects to hit.
935+
// Trying to see if any [true, false, true] occurs.
936+
await act(async () => {
937+
await waitMs(1)
938+
})
939+
940+
await act(async () => {
941+
await waitMs(1)
942+
})
943+
944+
await act(async () => {
945+
await waitMs(1)
946+
})
947+
948+
// Find if at any time the isLoading state has reverted
949+
// E.G.: `[..., true, false, ..., true]`
950+
// ^^^^ ^^^^^ ^^^^
951+
const firstTrue = states.indexOf(true)
952+
const firstFalse = states.slice(firstTrue).indexOf(false)
953+
const revertedState = states.slice(firstFalse).indexOf(true)
954+
955+
expect(
956+
revertedState,
957+
`Expected isLoading state to never revert back to true but did after ${revertedState} renders...`,
958+
).toBe(-1)
959+
})
960+
910961
describe('Hook middleware requirements', () => {
911962
let mock: MockInstance
912963

0 commit comments

Comments
 (0)