reduxjs / redux-toolkit

The official, opinionated, batteries-included toolset for efficient Redux development
https://redux-toolkit.js.org
MIT License
10.73k stars 1.17k forks source link

RTKQ: useLazyQuery - calling of trigger function with different arguments makes unsubscribe #4280

Closed greskosa closed 1 month ago

greskosa commented 7 months ago

Hello 👋

Documentation for useLazyQuery says about one of the feature:

'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts

But there is no mention about unsubscribing when trigger function was called a few times with different arguments.

Example:

const preferCacheValue = true; // use the value from a cache if exists
const [trigger, { data }] = useLazyEnpointQuery();

trigger({ id: 1 }, preferCacheValue); 
// asynchronous fetching of data for id 1 and putting it to the cache

trigger({ id: 2 }, preferCacheValue); 
// first action [nameOfApi]/subscriptions/unsubscribeQueryResult is called
// that causes clearing of cache for previous id, and then
// asynchronous fetching of data for id 2 and putting it to the cache

It always makes unsubscribe and clearing of cache for previous id but I need to keep both results in the cache and clear them only on component unmount. Is there any way to control that?

Thanks for help!

phryneas commented 7 months ago

No, that's not supported. The hooks are generally always only meant to monitor the "last result", so any results previous to that will be unsubscribed.

You probably need hand-written logic that dispatches endpoint.initiate() calls.

greskosa commented 7 months ago

@phryneas thanks for the quick reply. Is there any chance to update the documentation to have a more precise description of how cache clearing works for this particular case?

phryneas commented 7 months ago

A PR would be very welcome.