Open History to see the last commit
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```