Skip to Content
TelamonJS

Data Layer (React Query)

API client, query, mutations and cache invalidation behind every CrudConfig module

The browser talks to your REST API directly, in one hop, and React Query owns the cache. A module's data layer has three parts:

PartWhereJob
API clientlib/api/[entity]-client.tsThe only file that calls fetch() for the entity. Returns raw entities, throws on errors
queryCrudConfig.query in config.tsxLoads the list: resolves PaginatedResponse<T>
mutationsCrudConfig.mutations in config.tsxAdapts the client to the { success, message?, data? } contract and declares what to invalidate

config.tsx starts with 'use client': ListPage turns query and mutations into React Query hooks. The app's QueryClient and providers are covered in Provider Setup; a complete client is in the Quick Start.

Server Actions are not a data layer

query and mutations are required on CrudConfig: the data layer is React Query talking to your REST API, not Server Actions or unstable_cache.


The API Client

Keep the client thin: build the URL, send cookies, parse the response, and throw when the response is not OK. Do not shape results for the UI here; that happens in mutationFn.

lib/api/orders-client.ts
import type { PaginatedResponse, PaginationParams } from '@telamonjs/ui'

const BASE_URL = `${process.env.NEXT_PUBLIC_API_URL}/orders`

async function parse<T>(res: Response, fallback: string): Promise<T> {
  if (!res.ok) {
    const body = await res.json().catch(() => null)
    throw new Error(body?.message ?? fallback) // this message reaches the error toast
  }
  return res.status === 204 ? (undefined as T) : res.json()
}

export const ordersApi = {
  list: (params: PaginationParams): Promise<PaginatedResponse<Order>> => {
    const qs = new URLSearchParams({ page: String(params.page), pageSize: String(params.pageSize) })
    if (params.search) qs.set('search', params.search)
    if (typeof params.sortBy === 'string') qs.set('sortBy', params.sortBy)
    if (params.sortOrder) qs.set('sortOrder', params.sortOrder)
    for (const [key, value] of Object.entries(params.filters ?? {})) {
      if (value !== undefined && value !== null && value !== '') qs.set(key, String(value))
    }
    return fetch(`${BASE_URL}?${qs}`, { credentials: 'include' }).then(res => parse(res, 'Failed to load orders'))
  },
  get: (id: string): Promise<Order> =>
    fetch(`${BASE_URL}/${id}`, { credentials: 'include' }).then(res => parse(res, 'Order not found')),
  // create / update / delete follow the same shape and return the raw entity (or nothing)
}
  • credentials: 'include' sends the session cookie; the API validates it (see Auth for the NestJS guard).
  • The library reads the error message from Error.message, a NestJS body { message: string | string[] }, an axios-style response.data.message, or errors: Record<string, string[]>. Throw something that carries the backend's message and the toast shows it.
  • The list endpoint pages, searches, sorts and filters on the server. The browser never imports Prisma.

query

query: {
  queryKey: ['orders'],
  queryFn: ordersApi.list,
  staleTime: 30_000, // default: 5_000
},
KeyPurpose
queryKeyBase key. ListPage appends the current page, search, sort and filters to it
queryFnReceives ListQueryParams (page, pageSize, search?, sortBy?, sortOrder?, filters?) and resolves PaginatedResponse<T>
staleTimeMilliseconds before a cached page is refetched. Default 5_000
refetchIntervalPolling interval, or false. Paginated table only
optionsExtra useQuery options. Paginated table only

Infinite scroll ignores refetchInterval and options

The default infinite list only reads queryKey, queryFn and staleTime. For a polling list, set list.infiniteScroll: false, or invalidate the key yourself on an interval.

ListPage always sends sortBy as a single column name (a string), so ListQueryParams is PaginationParams with sortBy?: string. A client whose own params type says sortBy?: string, page?: number or extra optional filter keys is a queryFn as is — no wrapper, no cast:

query: { queryKey: ['orders'], queryFn: ordersApi.list },

asQueryFn (an unchecked cast) is only left for a client that still does not fit, such as one whose result is typed differently from PaginatedResponse<T>.

An endpoint that answers a plain array

For a short list whose endpoint does not page (sub-lists, queues, lookups), wrap the fetch in arrayQueryFn instead of hand-building a one-page PaginatedResponse. It fetches the array and does the search, filters, sort and paging in memory:

import { arrayQueryFn } from '@telamonjs/ui'

query: {
  queryKey: ['members', teamId],
  queryFn: arrayQueryFn(() => teamsApi.members(teamId), {
    searchFields: ['name', 'email'], // default: the row's top-level string/number values
  }),
},
  • Search: case- and accent-insensitive substring over searchFields (dotted paths work).
  • Filters: equality per key, compared as strings (toolbar values are strings, so 'true' matches true); empty values are skipped, and the toolbar's "all" choice never reaches a queryFn. A key that fetchAll consumes itself (a parent id in filters) and the rows do not carry: list the keys that should filter in filterFields ([] for none).
  • Sort: by sortBy — numbers, dates and booleans by value, text with localeCompare, empty values last. A nested column needs list.sortParam: 'path' so sortBy is the dotted path.
  • fetchAll receives the ListQueryParams, so it can still forward a scope or a search the endpoint understands.

There is no cache: every page request calls fetchAll again. With the infinite list's default page size most such lists load in one request; a list that outgrows that wants server paging.

What sortBy carries

list.sortParam picks what a column's sort looks like on the wire. It applies everywhere the list sends its sort: queryFn, exportAll, list.onExport, toolbarContent and the URL (urlSync).

ColumnsortParam: 'id' (default)sortParam: 'path'
accessorKey: 'name'namename
accessorKey: 'created_at'created_atcreated_at
accessorKey: 'customer.name'customer_namecustomer.name
accessorKey: '_count.items'_count_items_count.items
id: 'owner', accessorKey: 'owner.name'ownerowner.name
id: 'total', accessorFn (no accessorKey)totaltotal

In 'id' mode the field is TanStack's column id: a dotted accessorKey arrives with every . turned into _, so a backend cannot tell customer_name (nested) from created_at (snake_case). 'path' sends the data path itself. Saved views and defaultSortBy may hold either form in both modes (defaultSortBy: 'customer.name' highlights the right header).

list: { columns, sortParam: 'path' }, // opt in per list; the default in the next major

Before turning on 'path'

Check that the endpoint accepts the dotted form. A backend that whitelists customer_name will silently fall back to its default order for customer.name: add the dotted key next to the old one (customer.name and customer_name) and keep both while old clients are around. Order by a relation count with { items: { _count: 'asc' } } for _count.items.

Server helpers

createPaginatedResponse(data, total, page, pageSize) builds the response. buildPrismaOrderBy(sortBy, sortOrder, sortableFields?) and buildPrismaOrderByMulti(sortFields, sortableFields?) turn either wire form into a Prisma orderBy:

  • A value with a dot is a data path, used as-is: customer.name → { customer: { name } }, order_item.created_at → { order_item: { created_at } }.
  • _count.items → { items: { _count: 'asc' } } (also customer._count.orders), in either form.
  • A value listed in sortableFields is used as-is, so created_at stays a column.
  • Any other underscored value is decoded as a legacy column id (customer_name → customer.name); with sortableFields, only when the decoded path is listed. Without sortableFields, created_at becomes created.at: pass the list when you have snake_case fields.

createPaginationContext(...).createPaginatedService(config) accepts any sortBy the client sends unless you set sortableFields: ['name', 'customer.name', 'created_at'] (data paths). A legacy id passes when its dotted form is listed (customer_name for customer.name), so one whitelist serves both modes; anything else falls back to defaultOrderBy. An invalid sortOrder always falls back to defaultOrderDirection.


mutations

Each mutationFn resolves a fixed shape. The API client returns raw entities, so adapt inside the mutationFn:

mutations: {
  create: {
    mutationFn: async data => ({ success: true, message: 'Order created', data: await ordersApi.create(data) }),
    invalidates: [['orders']],
  },
  update: {
    mutationFn: async ({ id, data }) => ({ success: true, data: await ordersApi.update(id, data) }),
    invalidates: [['orders'], id => ['orders', id]],
  },
  delete: {
    mutationFn: async ({ id }) => {
      await ordersApi.delete(id)
      return { success: true }
    },
    invalidates: [['orders']],
  },
  getForEdit: ordersApi.get,
  getForView: ordersApi.get,
},
KeyReceivesResolves
create.mutationFnthe form values{ success, message?, data? }: data is the entity
update.mutationFn{ id, data }{ success, message?, data? }: data is the entity
delete.mutationFn{ id }{ success, message? }
getForEditidthe record the edit form needs (nested relations included): the form data or the entity itself (TFormData | T)
getForViewidthe record the view dialog shows

When your actions answer something other than the entity in data ({ id }, or nothing in particular), say so once in the config's third type argument, and onSuccess gets that type:

export const ordersConfig: CrudConfig<Order, OrderFormData, { id: string }> = {
  // ...
  mutations: {
    create: { mutationFn: ordersApi.create, invalidates: [['orders']] }, // resolves { success, data?: { id } }
  },
}

Use unknown when the actions return various shapes. A component or helper that takes any of your configs types it as CrudConfigWithAnyForm<T> (what ListPage takes), not CrudConfig<T, F>, which expects the entity in data.

What the library does around each mutation:

  • On success it invalidates every key in invalidates, calls your onSuccess(result, variables), shows a success toast when the result has a message, and waits for the list's first refetch attempt before resolving (see Cache Invalidation).
  • On error (the mutationFn throws) it calls your onError(error, variables) and shows an error toast with the error's message.
  • A result with success: false keeps the form open and shows its message as a toast and an inline error.
  • Resolving the raw entity, without success, leaves the dialog open with no feedback, even though the record was saved.

Every mutation is optional. Leave out create (or update, delete) and the matching button is not rendered.


Cache Invalidation

invalidates lists query keys, or functions that receive the mutated record's id and return a key (update and delete pass the id; create passes undefined).

  • Include the list's queryKey. Because ListPage appends the params to it, invalidating ['orders'] refreshes every cached page, search and filter of that list. A key that doesn't match leaves the list stale after a save.
  • Use hierarchical keys for everything about one entity: ['orders'] for lists, ['orders', id] for a detail, ['orders', 'stats'] for aggregates. Invalidating ['orders'] then reaches all of them.
  • The dialog closes over a fresh list. The mutation resolves once each invalidated query that is on screen finished its first refetch attempt, so the saved row is already in the list when the dialog closes. A failing refetch never turns the save into an error and never holds the dialog through its retries: the mutation resolves on the first failure and React Query keeps retrying in the background.

The list also refreshes on its own after a successful custom row action (actionsConfig.custom) or bulk action; return { success: false } from the handler to skip that. Other queries (a dashboard, another module, a detail page) need an explicit invalidation:

'use client'
import { useQueryClient } from '@tanstack/react-query'
import { ListPage } from '@telamonjs/ui'

export default function OrdersPage() {
  const queryClient = useQueryClient()
  return (
    <ListPage
      config={config}
      // runs after every list refresh, including the one after an action
      onRefreshAction={async () => {
        await queryClient.invalidateQueries({ queryKey: ['dashboard', 'orders'] })
      }}
    />
  )
}

Import useQueryClient, useQuery and the rest from @tanstack/react-query directly. The library does not re-export React Query, on purpose: a second copy causes "No QueryClient set".


Errors

Where it failsWhat handles it
The list queryListPage renders an error state with a retry button
A CRUD mutationThe library toasts the message; add onError only for extra behavior
Rendering (a cell, dialog content)ListPage wraps itself in an error boundary (errorBoundary, default true; errorFallback customizes it)
An automatic background refreshLogged, never toasted. Refresh on window focus is opt-in: disableAutoRefresh={false}
A button you wire yourselftry/catch, a loading state that disables the button, and a toast for success and failure

Every query and mutation the library runs carries meta: { skipErrorToast: true }. If the app's QueryClient has a global onError toast, skip those or users see the error twice: see Provider Setup.


Testing

Everything in config.tsx is a named export, so the data layer can be tested without rendering: mock the API client and call the adapters directly.

config.test.ts
import { describe, expect, it, vi } from 'vitest'
import { config, validationSchema } from './config'

vi.mock('@/lib/api/orders-client', () => ({
  ordersApi: { create: vi.fn(async (data: unknown) => ({ id: '1', ...(data as object) })) },
}))

describe('orders config', () => {
  it('create resolves the mutation contract, not the raw entity', async () => {
    const result = await config.mutations.create?.mutationFn({ customer: 'ACME', total: 10 })
    expect(result).toMatchObject({ success: true, data: { id: '1' } })
  })

  it('rejects an order without a customer', () => {
    expect(validationSchema.safeParse({ total: 10 }).success).toBe(false)
  })
})

To render ListPage in a test, wrap it in the same providers the app uses (see Provider Setup), with a QueryClient that does not retry.


Checklist

  • config.tsx starts with 'use client'
  • The API client is the only fetch() for the entity, sends credentials: 'include' and throws with the backend's message
  • queryFn resolves PaginatedResponse<T>, not an array
  • Every mutationFn resolves { success, message?, data? }
  • Every invalidates includes the list's queryKey
  • React Query is imported from @tanstack/react-query, never through the library

On this page