query: Tanstack Query for Svelte 5 does not rerender when adding a dependency variable
Describe the bug
Issue Description:
Problem: When utilizing the createInfiniteQuery client to manage infinite queries, there is an issue with updating the query despite the addition of a dependency variable in the query key.
Steps to Reproduce:
Initialize a query using createInfiniteQuery. Define a queryKey that includes generic variables. Implement the queryFn function to handle data retrieval based on certain conditions. Attempt to update the query based on changes in the dependency variable within the queryKey.
Actual Behavior: Despite adding the dependency variable to the queryKey, the query does not update as expected when the variable changes.
Code Snippet:
javascript
let query = createInfiniteQuery({
queryKey: ['Resource', dependencyVariable],
queryFn: async ({ pageParam }) => {
// Implementation omitted for brevity
},
getNextPageParam(lastPage) {
// Implementation omitted for brevity
},
initialPageParam: null as string | null | undefined,
initialDataUpdatedAt: () => Date.now(),
});
Environment:
Framework/Libraries: SVELTE 5 Possible Solutions:
Review the implementation of createInfiniteQuery to ensure proper handling of dependency variables. Check for any inconsistencies or errors in the query key setup. Consider alternative approaches for managing infinite queries that may better accommodate dynamic updates.
Your minimal, reproducible example
I have added an example code below
Steps to reproduce
Steps to Reproduce:
Initialize a query using createInfiniteQuery. Define a queryKey that includes generic variables. Implement the queryFn function to handle data retrieval based on certain conditions. Attempt to update the query based on changes in the dependency variable within the queryKey. Expected Behavior: The query should update accordingly when there are changes in the dependency variable included in the queryKey.
Expected behavior
Expected Behavior: The query should update accordingly when there are changes in the dependency variable included in the queryKey.
How often does this bug happen?
Every time
Screenshots or Videos
test
Platform
Any platform
Tanstack Query adapter
None
TanStack Query version
TypeScript version
5.4.3
Additional context
Additional Context: This issue impacts the ability to dynamically update queries based on changing dependency variables, hindering the functionality of the application.
About this issue
- Original URL
- State: open
- Created 3 years ago
- Reactions: 6
- Comments: 29 (9 by maintainers)
To my knowledge, Tanstack Query has yet to support Svelte 5 runes, so directly feeding
$state(assuming dependencyVariable is$state) won’t yield the desired results.The Tanstack Query 5 documentation mentions you can pass options as a
Svelte Storeto make it reactive. While not very ergonomic, it is workable.Alternatives like Svelte 4 reactive statements or re-creating the query in a
$effectwon’t work because svelte’scontextbecomes unavailable after the component initialization is complete. (this accidentally did work in early versions of svelte 5)To make it a bit more ergnomic you can simplify the creation of a reactive store from your runes with a function like:
and then do something like:
However, note that the above example is for
createQuery. ForcreateInfiniteQuery, it appears to be a bit trickier. You might expect something like this to work:However, this gives me a lot of type errors, suggesting it is not the way to do it.
An additional example in the documentation specifically demonstrating how to use
createInfiniteQueryreactively would be very helpful.Why is noone using this:
@SaintPepsi here’s the function as I’m actually using it:
utils.svelte.ts
Usage could then be something like:
+page.svelte
I’m using Svelte 5 and needed to derive one of the variables in my
createQuery. To achieve this, I tried wrappingcreateQueryin$derived. However, I encountered an error becausecreateQueryusesgetContextinternally, andgetContextcan only be called on mount. Wrapping each use of the component with a derived query in{#key}was not a desirable solution.The example provided by @nicksulkers wasn’t working for me, as it resulted in the error: “
$effect()can only be used as an expression statement.”To solve this, I created an abstraction using a
readableandqueryClient.ensureQueryData. This approach functions similarly but doesn’t require a context, so it avoids breaking in Svelte 5’s runes and re-rendering. The downside is that I no longer have state data, just the data I want or null. Given my limited coding time outside of work, this was the best solution I could come up with.Here’s the implementation:
I then use it like this:
I wish I know of a way to just do this:
I was tired of wrapping every query and mutation with a
fromStore(...)and all this kinds of stuff so i created a svelte 5 version of svelte query: david-plugge/svelte-5-query. It works great and is so easy to use, no$prefix, no wrapper, no anything. I’d be happy to contribute to this repository if my solution is acceptable 😃So if I understand correctly, you want to automatically update the data every 3 seconds?
You could perhaps use a interval to just trigger $query.refetch every x time,
@sgcullen your example works since there is no $state being used in fetchData. Let me expand a bit on your example:
Now you’d want
queryFnto run, whenever activeIndex changes, but it doesn’t.In early alpha versions of svelte 5 you could just add a
$derivedaround thecreateQuerymethod to just re-create it, but… that no longer works because it relies on sveltes’getContext.The solution mentioned in the tanstack docs to make the
createQueryoptions a readable store isn’t very ergonomic. ThereactiveQueryArgsin posts above attempts to make this more bearable. And thus we end up with:@frederikhors Your error is likely due to
where getTeam (and specifically it’s parameter) is executed immediately, before data contains a meaningful value.
You probably intended to do something like this:
where getTeam only gets called after the queryFn is triggered and we are certain data is valid because of the “enabled” property.
You’ll probably want to do the same thing for your “getPlayer”.
I was just reading through the source code and realised I can also just pass
queryClientas second parameter tocreateQuery@nicksulkers is
reactiveQueryArgsin a.svelte.tsfile?