Skip to content

TanStack Query

Goal: TanStack Query in a page, with its first data coming from the page's load and its cache refreshed after a change. The runnable samples are examples/data-react/, examples/data-vue/, examples/data-preact/, examples/data-solid/ and examples/data-svelte/; the library is a devDependency of each example, and Hamur has no module for it.

When Hamur's own data is enough: useAsyncData(handler, input) reads, useAction or Form changes and refreshes the page, router.refresh(key) re-runs what depends on a key, and meta.staleTime keeps a page's data between navigations (Data). Reach for TanStack Query when components need what that does not give: a cache shared by key across pages, retries, optimistic updates with rollback, infinite queries, or the devtools. The two work together; a handler is the function both call.

  1. Make one QueryClient for each request. A module-level client would be shared by every request on the server, so create it where the app renders. In React and Preact that is a useState initializer in the root component (app/app.tsx, Root component); in Solid the root component body; in Svelte app/app.svelte:
tsx
import { useState } from "react"
import { Outlet } from "@hamur/adapter-react"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { SWRConfig } from "swr"

export default function App() {
  const [queryClient] = useState(() => new QueryClient())
  return (
    <QueryClientProvider client={queryClient}>
      <SWRConfig value={{ provider: () => new Map() }}>
        <Outlet />
      </SWRConfig>
    </QueryClientProvider>
  )
}
svelte
<script lang="ts">
  import { Outlet } from "@hamur/adapter-svelte"
  import { QueryClient, QueryClientProvider } from "@tanstack/svelte-query"

  const client = new QueryClient()
</script>

<QueryClientProvider {client}>
  <Outlet />
</QueryClientProvider>

Vue has no provider component. Install VueQueryPlugin in the app:adapter hook, which gets Vue's App once for each request on the server and once in the browser (App setup per adapter):

ts
import { definePlugin } from "hamur/app"
import { QueryClient, VueQueryPlugin } from "@tanstack/vue-query"
import type { App } from "vue"

export default definePlugin((app) => {
  app.hooks.hook("app:adapter", (instance) => {
    ;(instance as App).use(VueQueryPlugin, { queryClient: new QueryClient() })
  })
})
  1. Seed the query from the page's load. The load calls the handler, so the server render and the first browser render have the data, and the data is in the page payload (What goes into the payload). The page passes it as initialData and sets staleTime, or the query refetches as soon as it mounts:
ts
import type { Load } from "hamur/app"
import { listTodos } from "#server"

export const load = (async () => ({ todos: await listTodos() })) satisfies Load
tsx
import { useState } from "react"
import { useData } from "@hamur/adapter-react"
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
import type { Todo } from "../../shared/todo.ts"
import { addTodo, listTodos } from "#server"

export default function Todos() {
  const { todos: seed } = useData<{ todos: Todo[] }>()
  const queryClient = useQueryClient()
  const [title, setTitle] = useState("")
  const todos = useQuery({ queryKey: ["todos"], queryFn: () => listTodos(), initialData: seed, staleTime: 30_000 })
  const add = useMutation({
    mutationFn: (value: string) => addTodo({ title: value }),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ["todos"] }),
  })

  return (
    <main>
      <h1>TanStack Query</h1>
      <ul>
        {todos.data.map((todo) => (
          <li key={todo.id}>{todo.title}</li>
        ))}
      </ul>
      <form
        onSubmit={(event) => {
          event.preventDefault()
          add.mutate(title)
          setTitle("")
        }}
      >
        <input value={title} onChange={(event) => setTitle(event.target.value)} />
        <button disabled={add.isPending}>Add</button>
      </form>
    </main>
  )
}

queryFn is the same handler, so a refetch in the browser is a request to it, and on the server it would be a call in the same process. TanStack Query does not fetch while the server renders, so without initialData the server HTML would show the pending state.

  1. Invalidate after a change. useMutation calls the handler, and onSuccess invalidates the key, which refetches the live queries that use it. A handler called this way does not go through useAction, so Hamur does not read the page again; the library's cache is the one you refresh. To let Hamur do it instead, call the handler with useAction and read the data with useData.

  2. Know which copy wins. initialData is read only when the query is not in the client's cache yet. After a client navigation back to the page, the load runs again (or not, under meta.staleTime), but the query keeps what it has until it is stale or invalidated. Use the same query key for the same data everywhere, and put the whole key in queryKey.

The other libraries differ only in the names and in how data reaches the sample; the load is the same file in each.

LibraryPackageReads the page's data withQuery
React@tanstack/react-queryuseData(), the valueuseQuery({ ... })
Preact@tanstack/preact-queryuseData(), the valueuseQuery({ ... })
Vue@tanstack/vue-queryuseData(), a ComputedRefuseQuery({ ... }), data is a ref
Solid@tanstack/solid-queryuseData(), an accessoruseQuery(() => ({ ... }))
Svelte@tanstack/svelte-queryuseData(), an object with valuecreateQuery(() => ({ ... }))

Vue:

vue
<script setup lang="ts">
import { ref } from "vue"
import { useData } from "@hamur/adapter-vue"
import { useMutation, useQuery, useQueryClient } from "@tanstack/vue-query"
import type { Todo } from "../../shared/todo.ts"
import { addTodo, listTodos } from "#server"

const seed = useData<{ todos: Todo[] }>()
const queryClient = useQueryClient()
const title = ref("")
const todos = useQuery({
  queryKey: ["todos"],
  queryFn: () => listTodos(),
  initialData: seed.value.todos,
  staleTime: 30_000,
})
const add = useMutation({
  mutationFn: (value: string) => addTodo({ title: value }),
  onSuccess: () => queryClient.invalidateQueries({ queryKey: ["todos"] }),
})

function submit() {
  add.mutate(title.value)
  title.value = ""
}
</script>

<template>
  <main>
    <h1>TanStack Query</h1>
    <ul>
      <li v-for="todo in todos.data.value" :key="todo.id">{{ todo.title }}</li>
    </ul>
    <form @submit.prevent="submit">
      <input v-model="title" />
      <button :disabled="add.isPending.value">Add</button>
    </form>
  </main>
</template>

Solid:

tsx
import { createSignal, For } from "solid-js"
import { useData } from "@hamur/adapter-solid"
import { useMutation, useQuery, useQueryClient } from "@tanstack/solid-query"
import type { Todo } from "../../shared/todo.ts"
import { addTodo, listTodos } from "#server"

export default function Todos() {
  const seed = useData<{ todos: Todo[] }>()
  const queryClient = useQueryClient()
  const [title, setTitle] = createSignal("")
  const todos = useQuery(() => ({
    queryKey: ["todos"],
    queryFn: () => listTodos(),
    initialData: seed().todos,
    staleTime: 30_000,
  }))
  const add = useMutation(() => ({
    mutationFn: (value: string) => addTodo({ title: value }),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ["todos"] }),
  }))

  return (
    <main>
      <h1>TanStack Query</h1>
      <ul>
        <For each={todos.data}>{(todo) => <li>{todo.title}</li>}</For>
      </ul>
      <form
        onSubmit={(event) => {
          event.preventDefault()
          add.mutate(title())
          setTitle("")
        }}
      >
        <input value={title()} onInput={(event) => setTitle(event.currentTarget.value)} />
        <button disabled={add.isPending}>Add</button>
      </form>
    </main>
  )
}

Svelte:

svelte
<script lang="ts">
  import { useData } from "@hamur/adapter-svelte"
  import { createMutation, createQuery, useQueryClient } from "@tanstack/svelte-query"
  import type { Todo } from "../../shared/todo.ts"
  import { addTodo, listTodos } from "#server"

  const seed = useData<{ todos: Todo[] }>()
  const queryClient = useQueryClient()
  let title = $state("")
  const todos = createQuery(() => ({
    queryKey: ["todos"],
    queryFn: () => listTodos(),
    initialData: seed.value.todos,
    staleTime: 30_000,
  }))
  const add = createMutation(() => ({
    mutationFn: (value: string) => addTodo({ title: value }),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ["todos"] }),
  }))

  function submit(event: SubmitEvent) {
    event.preventDefault()
    add.mutate(title)
    title = ""
  }
</script>

<main>
  <h1>TanStack Query</h1>
  <ul>
    {#each todos.data as todo (todo.id)}
      <li>{todo.title}</li>
    {/each}
  </ul>
  <form onsubmit={submit}>
    <input bind:value={title} />
    <button disabled={add.isPending}>Add</button>
  </form>
</main>

Preact:

tsx
import { useState } from "preact/hooks"
import { useData } from "@hamur/adapter-preact"
import { useMutation, useQuery, useQueryClient } from "@tanstack/preact-query"
import type { Todo } from "../../shared/todo.ts"
import { addTodo, listTodos } from "#server"

export default function Todos() {
  const { todos: seed } = useData<{ todos: Todo[] }>()
  const queryClient = useQueryClient()
  const [title, setTitle] = useState("")
  const todos = useQuery({ queryKey: ["todos"], queryFn: () => listTodos(), initialData: seed, staleTime: 30_000 })
  const add = useMutation({
    mutationFn: (value: string) => addTodo({ title: value }),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ["todos"] }),
  })

  return (
    <main>
      <h1>TanStack Query</h1>
      <ul>
        {todos.data.map((todo) => (
          <li key={todo.id}>{todo.title}</li>
        ))}
      </ul>
      <form
        onSubmit={(event) => {
          event.preventDefault()
          add.mutate(title)
          setTitle("")
        }}
      >
        <input value={title} onInput={(event) => setTitle(event.currentTarget.value)} />
        <button disabled={add.isPending}>Add</button>
      </form>
    </main>
  )
}

The handler the samples call is a plain defineHandler in server/todos.ts of each example:

ts
import { defineHandler } from "hamur/server"
import type { StandardSchemaV1 } from "hamur/server"
import type { Todo } from "../shared/todo.ts"

const todos: Todo[] = [{ id: 1, title: "Read the recipe" }]

const titleInput: StandardSchemaV1<unknown, { title: string }> = {
  "~standard": {
    version: 1,
    vendor: "recipe",
    validate: (value) => {
      const title = (value as { title?: unknown } | undefined)?.title
      return typeof title === "string" && title
        ? { value: { title } }
        : { issues: [{ message: "A title is required", path: ["title"] }] }
    },
  },
}

export const listTodos = defineHandler({
  method: "GET",
  handler: (): Todo[] => [...todos],
})

export const addTodo = defineHandler({
  input: titleInput,
  handler({ title }): Todo {
    const todo = { id: todos.length + 1, title }
    todos.push(todo)
    return todo
  },
})

See also: Data, Handlers, Plugins and hooks, SWR, Hydration.