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, variables will run once, unless they are referenced in your markup. To make a different variable or function reactive, you need to use [reactive declarations](https://svelte.dev/tutorial/reactive-declarations). This also applies to Svelte Query.
7β
8In the below example, the `refetchInterval` option is set from the variable `intervalMs`, which is edited by the input field. However, as the query is not told it should 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 endpoint = 'http://localhost:5173/api/data'
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 bind:value={intervalMs} type="number" />
26```
27β
28To solve this, you can prefix the query with `$: ` to tell the compiler it should be reactive.
29β
30```svelte
31<script lang="ts">
32 import { createQuery } from '@tanstack/svelte-query'
33β
34 let intervalMs = 1000
35β
36 const endpoint = 'http://localhost:5173/api/data'
37β
38 $: query = createQuery({
39 queryKey: ['refetch'],
40 queryFn: async () => await fetch(endpoint).then((r) => r.json()),
41 refetchInterval: intervalMs,
42 })
43</script>
44β
45<input bind:value={intervalMs} type="number" />
46```