SvelteStack / svelte-query

Performant and powerful remote data synchronization for Svelte
https://sveltequery.vercel.app
MIT License
813 stars 31 forks source link

Cache not working as expected #60

Closed albingroen closed 2 years ago

albingroen commented 2 years ago

This video shows 2 pages where both include the Threads component. The issue is that on first navigation the cache from the initial page doesn't seem to get used. If you go back though and then click a thread again, the list cache seem to get used.

For context, I am using SvelteKit

https://user-images.githubusercontent.com/19674362/140233638-36a03bba-a033-467b-a4c4-745531903b55.mp4

Threads.svelte

<script>
  import ListThread from "./ListThread.svelte";
  import { useQuery } from "@sveltestack/svelte-query";

  const getThreads = async () => {
    return fetch("/gmail/email")
      .then((res) => res.json())
      .then((res) => res);
  };

  const threadsResult = useQuery("threads", getThreads);
</script>

{#if $threadsResult.data}
  <ul class="threads divide-y">
    {#each $threadsResult.data.emails?.data.threads ?? [] as thread (thread.id)}
      <ListThread {thread} />
    {/each}
  </ul>
{:else if $threadsResult.error}
  <p>An error occurred!</p>
{:else if $threadsResult.isLoading}
  <p>...waiting</p>
{/if}

Am I misunderstanding something here or is something broken?

SomaticIT commented 2 years ago

Based on your feedback, I think that this is an expected behavior.

When you navigate to the "thread" page, the component is instatiated again, so the query re-runs. When you navigate back, the old component is re-used, so the query is not re-executed.

I think, if you add a link to go back (not using the history), you will have the same behavior: query will re-run on every navigation. Can you try?

If you want to enforce the use of cache between navigations, you should use a combination of staleTime and cacheTime options:

// This query will re-run only every 1 minute
const threadsResult = useQuery("threads", getThreads, {
  staleTime: 60000, /* 1 minute */
  cacheTime: 60000 /* 1 minute */
});