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

Refetch should not happen if no active subscribers #1974

Merged
merged 4 commits into from
Feb 1, 2022
Merged
Show file tree
Hide file tree
Changes from 2 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
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
import { QueryStatus } from '../apiState'
import type { QueryCacheKey } from '../apiState'
import { onFocus, onOnline } from '../setupListeners'
import type { SubMiddlewareApi, SubMiddlewareBuilder } from './types'

export const build: SubMiddlewareBuilder = ({
reducerPath,
context,
api,
refetchQuery,
}) => {
const { removeQueryResult } = api.internalActions

return (mwApi) =>
(next) =>
(action): any => {
Expand Down Expand Up @@ -35,24 +39,27 @@ export const build: SubMiddlewareBuilder = ({
const querySubState = queries[queryCacheKey]
const subscriptionSubState = subscriptions[queryCacheKey]

if (
!subscriptionSubState ||
!querySubState ||
querySubState.status === QueryStatus.uninitialized
)
return

const shouldRefetch =
Object.values(subscriptionSubState).some(
(sub) => sub[type] === true
) ||
(Object.values(subscriptionSubState).every(
(sub) => sub[type] === undefined
) &&
state.config[type])

if (shouldRefetch) {
api.dispatch(refetchQuery(querySubState, queryCacheKey))
if (!subscriptionSubState || !querySubState) return
AlexanderArvidsson marked this conversation as resolved.
Show resolved Hide resolved

if (Object.keys(subscriptionSubState).length === 0) {
api.dispatch(
removeQueryResult({
queryCacheKey: queryCacheKey as QueryCacheKey,
})
)
} else if (querySubState.status !== QueryStatus.uninitialized) {
const shouldRefetch =
Object.values(subscriptionSubState).some(
(sub) => sub[type] === true
) ||
(Object.values(subscriptionSubState).every(
(sub) => sub[type] === undefined
) &&
state.config[type])

if (shouldRefetch) {
api.dispatch(refetchQuery(querySubState, queryCacheKey))
}
AlexanderArvidsson marked this conversation as resolved.
Show resolved Hide resolved
}
}
})
Expand Down
22 changes: 22 additions & 0 deletions packages/toolkit/src/query/tests/cleanup.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,28 @@ test('data is removed from store after 60 seconds', async () => {
expect(getSubStateA()).toBeUndefined()
})

test('data is removed from store if refetch without active subscribers', async () => {
expect(getSubStateA()).toBeUndefined()

const { unmount } = render(<UsingA />, { wrapper: storeRef.wrapper })
await waitFor(() =>
expect(getSubStateA()?.status).toBe(QueryStatus.fulfilled)
)

unmount()

jest.advanceTimersByTime(20000)

expect(getSubStateA()?.status).toBe(QueryStatus.fulfilled)

await storeRef.store.dispatch(api.endpoints.a.initiate())

jest.advanceTimersByTime(2000)

console.log(storeRef.store.getState())
expect(getSubStateA()).toBeUndefined()
})

test('data stays in store when component stays rendered while data for another component is removed after it unmounted', async () => {
expect(getSubStateA()).toBeUndefined()
expect(getSubStateB()).toBeUndefined()
Expand Down
43 changes: 43 additions & 0 deletions packages/toolkit/src/query/tests/refetchingBehaviors.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ const defaultApi = createApi({

const storeRef = setupApiStore(defaultApi)

let getIncrementedAmountState = () =>
storeRef.store.getState().api.queries['getIncrementedAmount(undefined)']

afterEach(() => {
amount = 0
})
Expand Down Expand Up @@ -177,6 +180,46 @@ describe('refetchOnFocus tests', () => {
expect(screen.getByTestId('amount').textContent).toBe('2')
)
})

test('useQuery hook cleans data if refetch without active subscribers', async () => {
let data, isLoading, isFetching

function User() {
;({ data, isFetching, isLoading } =
defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, {
refetchOnFocus: true,
}))
return (
<div>
<div data-testid="isLoading">{String(isLoading)}</div>
<div data-testid="isFetching">{String(isFetching)}</div>
<div data-testid="amount">{String(data?.amount)}</div>
</div>
)
}

const { unmount } = render(<User />, { wrapper: storeRef.wrapper })

await waitFor(() =>
expect(screen.getByTestId('isLoading').textContent).toBe('true')
)
await waitFor(() =>
expect(screen.getByTestId('isLoading').textContent).toBe('false')
)
await waitFor(() =>
expect(screen.getByTestId('amount').textContent).toBe('1')
)

unmount()

expect(getIncrementedAmountState()).not.toBeUndefined()

act(() => {
fireEvent.focus(window)
})

expect(getIncrementedAmountState()).toBeUndefined()
})
})

describe('refetchOnReconnect tests', () => {
Expand Down