How can I subscribe to a specific cache entry without triggering a request? #4213
-
In my component, I want to display the data from my endpoint only if it is already present in the cache. I don't want this component to trigger a request when it mounts. But I do want it to create a subscription, so that the data doesn't get removed from the cache and disappear from the UI while this component is still mounted. From what I can tell, there is no single hook provided by RTK query that satisfies these requirements. I think I could use useLazyQuerySubscription in combination with useQueryState, but there's something I'm not sure about with that approach: Does useLazyQuerySubscription prevent ALL entries from the given cache from being removed from the cache? I think it must do, because you don't pass the query args directly when calling the hook (so how would it know which cache entry to subscribe to?). Ideally I would only create a subscription to the specific cache entry that I'm interested in. Or maybe I'm misunderstanding how the subscriptions work. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
my bad, it looks like that is just the store data and not a query subscription. |
Beta Was this translation helpful? Give feedback.
-
Generally we don't provide anything specific for this use case because by creating a subscription you're saying you want that data, so it only makes sense to fetch the data if it's not already there. I guess you could hack something together with useQueryState and useQuerySubscription, skipping your subscription if the state is uninitialized: const { data, isUninitialized } = useQueryState(arg)
const { refetch } = useQuerySubscription(arg, { skip: isUninitialized }) |
Beta Was this translation helpful? Give feedback.
useLazyQuerySubscription
doesn't subscribe until it's triggered.Generally we don't provide anything specific for this use case because by creating a subscription you're saying you want that data, so it only makes sense to fetch the data if it's not already there.
I guess you could hack something together with useQueryState and useQuerySubscription, skipping your subscription if the state is uninitialized: