query: [svelte] keepPreviousData not working

Describe the bug

The keepPreviousData options does not seem to work in the svelte-query. Even when set to true the data is empty until the new query is done.

I made the query reactive using the documentation here: https://tanstack.com/query/v4/docs/svelte/reactivity

I think it is because the current syntax will rerun the createQuery method and create a new query object each time any used variable changes, instead of subscribing to change within the already created query object, but I do not know enough about the inner workings of query-core and svelte-query to know if this is indeed an issue.

Your minimal, reproducible example

https://codesandbox.io/s/nifty-cloud-pxwjho?file=/App.svelte

Steps to reproduce

  1. Create a reactive query with a queryKey with a variable and keepPreviousData set to true
  2. Render the results to the DOM
  3. Update the variable
  4. All results are removed immediately removed from the DOM
  5. And rendered again when the new query result is available

Expected behavior

As a user, I expected the previous data be visible in the DOM during fetching of the updated data

How often does this bug happen?

Every time

Screenshots or Videos

No response

Platform

  • OS: Windows
  • Browsers: Chrome 109.0, Firefox 109.0

TanStack Query version

4.22.3

TypeScript version

4.9.4

Additional context

No response

About this issue

  • Original URL
  • State: closed
  • Created a year ago
  • Comments: 16 (4 by maintainers)

Most upvoted comments

I tried that and it didn’t work for me. I had a deeper look into this and, among other things, checked how tanstack/table handles it and they seem to use a writable store for the entire options object. I think this would also be a good idea for svelte-query. It would look something like this:

const options = writable({
  queryKey: ['test', [1]],
  queryFn: async ({ queryKey }) => {
    await sleep(100)
    return queryKey[1]
  },
  keepPreviousData: true,
})
const query = createQuery(options)

Within svelte files you can then simply update the options like so:

$options.queryKey[1] = [1, 2]

And outside of svelte files:

options.update((o) => ({ ...o, queryKey: ['test', [1, 2]] }))

If you do not need the reactivity you can still use a regular options object.

I made a PoC with a test that was failing before and working with these changes. I do not know query-core well though, so I’m not sure all changes are completely correct. You can check this here: https://github.com/TanStack/query/compare/main...chrislcs:query:main