trpc icon indicating copy to clipboard operation
trpc copied to clipboard

feat: tanstack db adapter

Open cabello opened this issue 4 months ago โ€ข 0 comments

Describe the feature you'd like to request

It might be too early because the project is in active development but I am looking into integrating https://github.com/TanStack/db into an existing trpc project.

tanstack DB is a new project that aims to keep a client data store so the app has local state for previous API calls, it would allow the app to load instantly with stale data and fetch the latest data in the background, similar to staleTime, keepPreviousData and other options that exist in tanstack query but designed for the use case of allowing the app to feel offline first.

from the quickstart example for tanstack query you see:

import { createCollection, eq, useLiveQuery } from '@tanstack/react-db'
import { queryCollectionOptions } from '@tanstack/query-db-collection'

// Define a collection that loads data using TanStack Query
const todoCollection = createCollection(
  queryCollectionOptions({
    queryKey: ['todos'],
    queryFn: async () => {
      const response = await fetch('/api/todos')
      return response.json()
    },
    getKey: (item) => item.id,
    onUpdate: async ({ transaction }) => {
      const { original, modified } = transaction.mutations[0]
      await fetch(`/api/todos/${original.id}`, {
        method: 'PUT',
        body: JSON.stringify(modified),
      })
    },
  })
)

This is outside the React component. The key one can get with getQueryKey, it's unclear to me when a query has params, like useQuery({ foo: 'foo', bar: 'bar' }) where they would go in this collection setup.

The benefits of the project are somewhat clear:

  • a list of records that exist in server would exist in your local app
  • when doing updates/inserts you could do optimistic ones (making the app feel faster)

Ideally this would be a client-side only solution with the server side receiving little to no modification.

Describe the solution you'd like to see

Expose an adapter so you can createCollection from a trpc query, you can call the mutation outside the hook on onInsert, onUpdate, onDelete. The query may expose a schema that is passed to createCollection as well.

Describe alternate solutions

Right now it would be to use isPending instead of isLoading from a query, to render stale data that is being refetched in the background, it would still cause the data to be completely refetched on a refresh of the page but it would allow navigation to look fast.

Additional information

I attempted to build a proof of concept with an existing project but I am not familiar with the trpc internals that would allow me to pass the right params when creating a collection.

๐Ÿ‘จโ€๐Ÿ‘งโ€๐Ÿ‘ฆ Contributing

  • [ ] ๐Ÿ™‹โ€โ™‚๏ธ Yes, I'd be down to file a PR implementing this feature!

cabello avatar Aug 13 '25 19:08 cabello