Skip to content
Closed
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
10 changes: 9 additions & 1 deletion packages/toolkit/src/query/react/buildHooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ import { UNINITIALIZED_VALUE } from './constants'
import type { ReactHooksModuleOptions } from './module'
import { useStableQueryArgs } from './useSerializedStableValue'
import { useShallowStableValue } from './useShallowStableValue'
import { useIsMounted } from './useIsMounted'

// Copy-pasted from React-Redux
const canUseDOM = () =>
Expand Down Expand Up @@ -1118,20 +1119,27 @@ export function buildHooks<Definitions extends EndpointDefinitions>({
}
}, [])

const getIsMounted = useIsMounted()

return useMemo(
() => ({
/**
* A method to manually refetch data for the query
*/
refetch: () => {
// If `refetch` gets called after the component is unmounted,
// this should be a no-op
if (!getIsMounted()) {
return
}
if (!promiseRef.current)
throw new Error(
'Cannot refetch a query that has not been started yet.',
)
return promiseRef.current?.refetch()
},
}),
[],
[getIsMounted],
)
}

Expand Down
16 changes: 16 additions & 0 deletions packages/toolkit/src/query/react/useIsMounted.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { useCallback, useLayoutEffect, useRef } from 'react'

export function useIsMounted(): () => boolean {
const mountedRef = useRef(false)
const get = useCallback(() => mountedRef.current, [])

useLayoutEffect(() => {
mountedRef.current = true

return () => {
mountedRef.current = false
}
}, [])

return get
}
22 changes: 22 additions & 0 deletions packages/toolkit/src/query/tests/buildHooks.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -812,6 +812,28 @@ describe('hooks tests', () => {
await screen.findByText('ID: 3')
})

test('refetch does not throw an error if run after unmount', async () => {
let refetchFunction: () => {}

function User() {
const { refetch } = api.endpoints.getUser.useQuery(1)

refetchFunction = refetch

return (
<div>
<button>Refetch</button>
</div>
)
}

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

unmount()

expect(() => refetchFunction()).not.toThrow()
})

test(`useQuery shouldn't call args serialization if request skipped`, async () => {
expect(() =>
renderHook(() => api.endpoints.queryWithDeepArg.useQuery(skipToken), {
Expand Down
Loading