Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

reactivity.md

49 lines1.6 KB

1---
2id: reactivity
3title: Reactivity
4---
5​
6Svelte uses a compiler to build your code which optimises rendering. By default, components run once, unless they are referenced in your markup. To be able to react to changes in options you need to use [stores](https://svelte.dev/docs/svelte-store).
7​
8In the below example, the `refetchInterval` option is set from the variable `intervalMs`, which is bound to the input field. However, as the query is not able to react to changes in `intervalMs`, `refetchInterval` will not change when the input value changes.
9​
10```svelte
11<script lang="ts">
12 import { createQuery } from '@tanstack/svelte-query'
13​
14 const endpoint = 'http://localhost:5173/api/data'
15​
16 let intervalMs = 1000
17​
18 const query = createQuery({
19 queryKey: ['refetch'],
20 queryFn: async () => await fetch(endpoint).then((r) => r.json()),
21 refetchInterval: intervalMs,
22 })
23</script>
24​
25<input type="number" bind:value={intervalMs} />
26```
27​
28To solve this, we can convert `intervalMs` into a writable store. The query options can then be turned into a derived store, which will be passed into the function with true reactivity.
29​
30```svelte
31<script lang="ts">
32 import { derived, writable } from 'svelte/store'
33 import { createQuery } from '@tanstack/svelte-query'
34​
35 const endpoint = 'http://localhost:5173/api/data'
36​
37 const intervalMs = writable(1000)
38​
39 const query = createQuery(
40 derived(intervalMs, ($intervalMs) => ({
41 queryKey: ['refetch'],
42 queryFn: async () => await fetch(endpoint).then((r) => r.json()),
43 refetchInterval: $intervalMs,
44 })),
45 )
46</script>
47​
48<input type="number" bind:value={$intervalMs} />
49```