Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
15 changes: 8 additions & 7 deletions packages/toolkit/src/query/react/buildHooks.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { AnyAction, ThunkAction, ThunkDispatch } from '@reduxjs/toolkit'
import { createSelector } from '@reduxjs/toolkit'
import type { Selector } from '@reduxjs/toolkit'
import type { Selector, Unsubscribe } from '@reduxjs/toolkit'
import type { DependencyList } from 'react'
import {
useCallback,
Expand Down Expand Up @@ -194,7 +194,8 @@ export type UseLazyQuery<D extends QueryDefinition<any, any, any, any>> = <
) => [
LazyQueryTrigger<D>,
UseQueryStateResult<D, R>,
UseLazyQueryLastPromiseInfo<D>
UseLazyQueryLastPromiseInfo<D>,
Unsubscribe | undefined
]

export type LazyQueryTrigger<D extends QueryDefinition<any, any, any, any>> = {
Expand Down Expand Up @@ -239,7 +240,7 @@ export type UseLazyQuerySubscription<
D extends QueryDefinition<any, any, any, any>
> = (
options?: SubscriptionOptions
) => readonly [LazyQueryTrigger<D>, QueryArgFrom<D> | UninitializedValue]
) => readonly [LazyQueryTrigger<D>, QueryArgFrom<D> | UninitializedValue, Unsubscribe | undefined]

export type QueryStateSelector<
R extends Record<string, any>,
Expand Down Expand Up @@ -772,7 +773,7 @@ export function buildHooks<Definitions extends EndpointDefinitions>({
}
}, [arg, trigger])

return useMemo(() => [trigger, arg] as const, [trigger, arg])
return useMemo(() => [trigger, arg, promiseRef.current?.unsubscribe] as const, [trigger, arg])
}

const useQueryState: UseQueryState<any> = (
Expand Down Expand Up @@ -835,16 +836,16 @@ export function buildHooks<Definitions extends EndpointDefinitions>({
useQuerySubscription,
useLazyQuerySubscription,
useLazyQuery(options) {
const [trigger, arg] = useLazyQuerySubscription(options)
const [trigger, arg, unsubscribe] = useLazyQuerySubscription(options)
const queryStateResults = useQueryState(arg, {
...options,
skip: arg === UNINITIALIZED_VALUE,
})

const info = useMemo(() => ({ lastArg: arg }), [arg])
return useMemo(
() => [trigger, queryStateResults, info],
[trigger, queryStateResults, info]
() => [trigger, queryStateResults, info, unsubscribe],
[trigger, queryStateResults, info, unsubscribe]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would suggest to make unsubscribe part of the info object and maybe give it a better name. Open to suggestions.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's some good advice, I missed the fact that info was already an object for some extra things so I can touch it without breaking anything 😄 not sure if extras is the best possible name though, waiting for further feedback!

)
},
useQuery(arg, options) {
Expand Down
67 changes: 67 additions & 0 deletions packages/toolkit/src/query/tests/buildHooks.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1027,6 +1027,73 @@ describe('hooks tests', () => {

expect(screen.getByTestId('error').textContent).toBe('')
})

test('useLazyQuery can be manually unsubscribed', async () => {
function User() {
const [getUser, { data, error }, _lastInfo, unsubscribe] =
api.endpoints.getUser.useLazyQuery()

const [unwrappedResult, setUnwrappedResult] = React.useState<
undefined | { name: string }
>()

const handleFetchClick = async () => {
const res = getUser(1)

const result = await res.unwrap()
setUnwrappedResult(result)
}

return (
<div>
<button onClick={handleFetchClick}>Fetch User</button>
<button onClick={unsubscribe}>Unsubscribe</button>
<div data-testid="result">{JSON.stringify(data)}</div>
<div data-testid="error">{JSON.stringify(error)}</div>
<div data-testid="unwrappedResult">
{JSON.stringify(unwrappedResult)}
</div>
</div>
)
}

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

const fetchButton = screen.getByRole('button', { name: 'Fetch User' })
fireEvent.click(fetchButton)

await waitFor(() => {
const dataResult = screen.getByTestId('result')?.textContent
const unwrappedDataResult =
screen.getByTestId('unwrappedResult')?.textContent

if (dataResult && unwrappedDataResult) {
expect(JSON.parse(dataResult)).toMatchObject({
name: 'Timmy',
})
expect(JSON.parse(unwrappedDataResult)).toMatchObject(
JSON.parse(dataResult)
)
}
})

expect(screen.getByTestId('error').textContent).toBe('')

const initialSubscriptionsCount = Object.keys(
storeRef.store.getState().api.subscriptions['getUser(1)']!
).length

expect(initialSubscriptionsCount).toEqual(1)

const unsubscribeButton = screen.getByRole('button', { name: 'Unsubscribe' })
fireEvent.click(unsubscribeButton)

const subscriptionsCountAfterUnsubscribing = Object.keys(
storeRef.store.getState().api.subscriptions['getUser(1)']!
).length

expect(subscriptionsCountAfterUnsubscribing).toEqual(0)
})
})

describe('useMutation', () => {
Expand Down