Open History to see the last commit
1---
2id: reactivity
3title: Reactivity
4---
5β
6Svelte uses a compiler to build your code which optimizes 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 let intervalMs = 1000
15β
16 const query = createQuery({
17 queryKey: ['refetch'],
18 queryFn: async () => await fetch('/api/data').then((r) => r.json()),
19 refetchInterval: intervalMs,
20 })
21</script>
22β
23<input type="number" bind:value={intervalMs} />
24```
25β
26To 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.
27β
28```svelte
29<script lang="ts">
30 import { derived, writable } from 'svelte/store'
31 import { createQuery } from '@tanstack/svelte-query'
32β
33 const intervalMs = writable(1000)
34β
35 const query = createQuery(
36 derived(intervalMs, ($intervalMs) => ({
37 queryKey: ['refetch'],
38 queryFn: async () => await fetch('/api/data').then((r) => r.json()),
39 refetchInterval: $intervalMs,
40 })),
41 )
42</script>
43β
44<input type="number" bind:value={$intervalMs} />
45```