Dispose of a resource held by a cached query #1109
Replies: 6 comments 8 replies
-
That's an interesting question. As far as I am aware, there is no dedicated callback that will be invoked when a query is evicted from the cache, but you can globally subscribe to the query cache and act on the specific removal there |
Beta Was this translation helpful? Give feedback.
-
@danielbrauer How did you end up solving this? I have the same need. |
Beta Was this translation helpful? Give feedback.
-
Isn't the problem also that if the queryFn is invoked because of a background refetch, you would create a new resource that overrides the old one without releasing it? So this doesn't necessarily have something to do with cache garbage collection, unless you combine it with infinite staleTime... |
Beta Was this translation helpful? Give feedback.
-
I ended up using this - https://gist.github.com/edzis/e97d83ee4eb7bf016f5dff165244ebd5
|
Beta Was this translation helpful? Give feedback.
-
this wouldn't work in the following case:
Every time you refetch a query, the |
Beta Was this translation helpful? Give feedback.
-
Here's a little helper which will call /**
* Subscribe to ``client``'s query cache and dispose of any values that have a
* ``[Symbol.dispose]`` method.
*
* Notes:
* - The exported ``SymbolDispose`` can be used if ``Symbol.dispose`` is not
* available.
* - The ``createDisposingObjectUrl`` helper can be used to create a disposable
* object URL.
*
* For example::
*
* const client = new QueryClient()
* queryClientDisposeOnCacheEvict(client)
*
* export const MyComponent = () => {
* const imageQuery = useQuery({
* queryFn: () => {
* const blob = await fetch(...).then(r => r.blob())
* // Note: see the ``createDisposingObjectUrl`` helper.
* const url = URL.createObjectURL(blob)
* return { url, [Symbol.dispose]: () => URL.revokeObjectURL(url) }
* },
* })
* ...
* }
*/ |
Beta Was this translation helpful? Give feedback.
-
Is there any way to have an action performed when a query result is overwritten or removed from the cache? I would like to have my query return URLs created with
URL.createObjectURL()
but currently can't see how I would issue the correspondingURL.revokeObjectURL()
to avoid leaking resources.Beta Was this translation helpful? Give feedback.
All reactions