Skip to content

Commit

Permalink
chore(svelte-query): Update reactivity docs and tests (#5683)
Browse files Browse the repository at this point in the history
  • Loading branch information
lachlancollins committed Jul 6, 2023
1 parent 43dc530 commit 0b2ddb5
Show file tree
Hide file tree
Showing 3 changed files with 114 additions and 67 deletions.
34 changes: 18 additions & 16 deletions docs/svelte/reactivity.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,45 +3,47 @@ id: reactivity
title: Reactivity
---

Svelte 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/docs/svelte-store).
Svelte 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).

In 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.
In 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.

```markdown
<script>
<script lang="ts">
import { createQuery } from '@tanstack/svelte-query'

let intervalMs = 1000

const endpoint = 'http://localhost:5173/api/data'

let intervalMs = 1000

const query = createQuery({
queryKey: ['refetch'],
queryFn: async () => await fetch(endpoint).then((r) => r.json()),
refetchInterval: intervalMs,
})
</script>

<input bind:value={intervalMs} type="number" />
<input type="number" bind:value={intervalMs} />
```

To 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.
To 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.

```markdown
<script>
<script lang="ts">
import { derived, writable } from 'svelte/store'
import { createQuery } from '@tanstack/svelte-query'
import type { CreateQueryOptions } from '@tanstack/svelte-query'

const endpoint = 'http://localhost:5173/api/data'

const queryOptions = writable({
queryKey: ['refetch'],
queryFn: async () => await fetch(endpoint).then((r) => r.json()),
refetchInterval: 1000,
}) satisfies CreateQueryOptions
const intervalMs = writable(1000)

const query = createQuery(queryOptions)
const query = createQuery(
derived(intervalMs, ($intervalMs) => ({
queryKey: ['refetch'],
queryFn: async () => await fetch(endpoint).then((r) => r.json()),
refetchInterval: $intervalMs,
}))
)
</script>

<input type="number" bind:value={$queryOptions.refetchInterval} />
<input type="number" bind:value={$intervalMs} />
```
23 changes: 10 additions & 13 deletions packages/svelte-query/src/__tests__/CreateQuery.svelte
Original file line number Diff line number Diff line change
@@ -1,27 +1,24 @@
<script lang="ts">
import { QueryClient } from '@tanstack/query-core'
import { setQueryClientContext } from '../context'
import { createQuery } from '../createQuery'
import type { QueryClient } from '@tanstack/query-core'
import type { CreateQueryOptions } from '../types'
export let options: CreateQueryOptions<any>
export let queryClient: QueryClient
const queryClient = new QueryClient()
setQueryClientContext(queryClient)
const query = createQuery(options)
const query = createQuery(options, queryClient)
</script>

{#if $query.isPending}
<p>Loading</p>
{:else if $query.isError}
<p>Error</p>
{:else if $query.isSuccess}
<p>Success</p>
{#if Array.isArray($query.data)}
{#each $query.data as item}
<p>{item}</p>
{/each}
{:else}
<p>{$query.data}</p>
{/if}
{/if}

<ul>
{#each $query.data ?? [] as entry}
<li>id: {entry.id}</li>
{/each}
</ul>
124 changes: 86 additions & 38 deletions packages/svelte-query/src/__tests__/createQuery.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { describe, expect, test } from 'vitest'
import { render, waitFor } from '@testing-library/svelte'
import { derived, writable } from 'svelte/store'
import { QueryClient } from '@tanstack/query-core'
import CreateQuery from './CreateQuery.svelte'
import { sleep } from './utils'
import type { CreateQueryOptions } from '../types'

describe('createQuery', () => {
test('Render and wait for success', async () => {
Expand All @@ -16,94 +16,142 @@ describe('createQuery', () => {
return 'Success'
},
},
queryClient: new QueryClient(),
},
})

await waitFor(() => {
expect(rendered.getByText('Loading')).toBeInTheDocument()
expect(rendered.queryByText('Loading')).toBeInTheDocument()
})

await waitFor(() => {
expect(rendered.getByText('Success')).toBeInTheDocument()
expect(rendered.queryByText('Success')).toBeInTheDocument()
})
})

test('Keep previous data when returned as placeholder data', async () => {
const options = writable({
queryKey: ['test', [1]],
queryFn: async ({ queryKey }) => {
test('Accept a writable store for options', async () => {
const optionsStore = writable({
queryKey: ['test'],
queryFn: async () => {
await sleep(10)
const ids = queryKey[1]
if (!ids || !Array.isArray(ids)) return []
return ids.map((id) => ({ id }))
return 'Success'
},
placeholderData: (previousData: { id: number }[]) => previousData,
}) satisfies CreateQueryOptions

const rendered = render(CreateQuery, { props: { options } })
})

await waitFor(() => {
expect(rendered.queryByText('id: 1')).not.toBeInTheDocument()
expect(rendered.queryByText('id: 2')).not.toBeInTheDocument()
const rendered = render(CreateQuery, {
props: {
options: optionsStore,
queryClient: new QueryClient(),
},
})

await waitFor(() => {
expect(rendered.queryByText('id: 1')).toBeInTheDocument()
expect(rendered.queryByText('id: 2')).not.toBeInTheDocument()
expect(rendered.queryByText('Success')).toBeInTheDocument()
})
})

test('Accept a derived store for options', async () => {
const writableStore = writable('test')

options.update((o) => ({ ...o, queryKey: ['test', [1, 2]] }))
const derivedStore = derived(writableStore, ($store) => ({
queryKey: [$store],
queryFn: async () => {
await sleep(10)
return 'Success'
},
}))

await waitFor(() => {
expect(rendered.queryByText('id: 1')).toBeInTheDocument()
expect(rendered.queryByText('id: 2')).not.toBeInTheDocument()
const rendered = render(CreateQuery, {
props: {
options: derivedStore,
queryClient: new QueryClient(),
},
})

await waitFor(() => {
expect(rendered.queryByText('id: 1')).toBeInTheDocument()
expect(rendered.queryByText('id: 2')).toBeInTheDocument()
expect(rendered.queryByText('Success')).toBeInTheDocument()
})
})

test('Accept a writable store for options', async () => {
const optionsStore = writable({
queryKey: ['test'],
test('Ensure reactivity when queryClient defaults are set', async () => {
const writableStore = writable(1)

const derivedStore = derived(writableStore, ($store) => ({
queryKey: [$store],
queryFn: async () => {
await sleep(10)
return 'Success'
return `Success ${$store}`
},
}) satisfies CreateQueryOptions
}))

const rendered = render(CreateQuery, {
props: {
options: optionsStore,
options: derivedStore,
queryClient: new QueryClient({
defaultOptions: { queries: { staleTime: 60 * 1000 } },
}),
},
})

await waitFor(() => {
expect(rendered.getByText('Success')).toBeInTheDocument()
expect(rendered.queryByText('Success 1')).toBeInTheDocument()
expect(rendered.queryByText('Success 2')).not.toBeInTheDocument()
})

writableStore.set(2)

await waitFor(() => {
expect(rendered.queryByText('Success 1')).not.toBeInTheDocument()
expect(rendered.queryByText('Success 2')).toBeInTheDocument()
})

writableStore.set(1)

await waitFor(() => {
expect(rendered.queryByText('Success 1')).toBeInTheDocument()
expect(rendered.queryByText('Success 2')).not.toBeInTheDocument()
})
})

test('Accept a derived store for options', async () => {
const writableStore = writable('test')
test('Keep previous data when returned as placeholder data', async () => {
const writableStore = writable<number[]>([1])

const derivedStore = derived(writableStore, ($store) => ({
queryKey: [$store],
queryKey: ['test', $store],
queryFn: async () => {
await sleep(10)
return 'Success'
return $store.map((id) => `Success ${id}`)
},
})) satisfies CreateQueryOptions
placeholderData: (previousData: string) => previousData,
}))

const rendered = render(CreateQuery, {
props: {
options: derivedStore,
queryClient: new QueryClient(),
},
})

await waitFor(() => {
expect(rendered.getByText('Success')).toBeInTheDocument()
expect(rendered.queryByText('Success 1')).not.toBeInTheDocument()
expect(rendered.queryByText('Success 2')).not.toBeInTheDocument()
})

await waitFor(() => {
expect(rendered.queryByText('Success 1')).toBeInTheDocument()
expect(rendered.queryByText('Success 2')).not.toBeInTheDocument()
})

writableStore.set([1, 2])

await waitFor(() => {
expect(rendered.queryByText('Success 1')).toBeInTheDocument()
expect(rendered.queryByText('Success 2')).not.toBeInTheDocument()
})

await waitFor(() => {
expect(rendered.queryByText('Success 1')).toBeInTheDocument()
expect(rendered.queryByText('Success 2')).toBeInTheDocument()
})
})
})

0 comments on commit 0b2ddb5

Please sign in to comment.