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, variables will 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/tutorial/writable-stores).
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```markdown
11<script>
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, create a store for the options and use it as input for the query. Update the options store when the value changes and the query will react to the change.
29​
30```markdown
31<script>
32 import { createQuery } from '@tanstack/svelte-query'
33​
34 const endpoint = 'http://localhost:5173/api/data'
35​
36 const queryOptions = writable({
37 queryKey: ['refetch'],
38 queryFn: async () => await fetch(endpoint).then((r) => r.json()),
39 refetchInterval: 1000,
40 })
41 const query = createQuery(queryOptions)
42​
43 function updateRefetchInterval(event) {
44 $queryOptions.refetchInterval = event.target.valueAsNumber
45 }
46</script>
47​
48<input type="number" on:input={updateRefetchInterval} />
49```