Skip to main content
Version: 3.0 Beta

TanStack Query

Overview​

TanStack Query is a powerful data-fetching library for the web frontend, supporting multiple UI frameworks like React, Vue, and Svelte.

info

TanStack Query integration only works with the RPC style API. Currently supported frameworks are: react, vue, and svelte.

This documentation assumes you have a solid understanding of TanStack Query concepts.

ZenStack's TanStack Query integration helps you derive a set of fully typed query and mutation hooks from your data model. The derived hooks work with the RPC style API and pretty much 1:1 mirror the ORM query APIs, allowing you to enjoy the same excellent data query DX from the frontend.

The integration provides the following features

  • Query and mutation hooks like useFindMany, useUpdate, etc.
  • All hooks accept standard TanStack Query options, allowing you to customize their behavior.
  • Standard, infinite, and suspense queries.
  • Automatic query invalidation upon mutation.
  • Automatic optimistic updates (opt-in).

Installation​

info

TanStack Query version 5.0.0 or later is required.

npm install @zenstackhq/tanstack-query@next

Context Provider​

You can configure the query hooks by setting up context. The following options are available on the context:

  • endpoint

    The endpoint to use for the queries. Defaults to "/api/model".

  • fetch

    A custom fetch function to use for the queries. Defaults to using built-in fetch.

  • logging

    Enable logging for debugging purposes. Defaults to false.

Example for using the context provider:

_app.tsx
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { QuerySettingsProvider, type FetchFn } from '@zenstackhq/tanstack-query/react';

// custom fetch function that adds a custom header
const myFetch: FetchFn = (url, options) => {
options = options ?? {};
options.headers = {
...options.headers,
'x-my-custom-header': 'hello world',
};
return fetch(url, options);
};

const queryClient = new QueryClient();

function MyApp({ Component, pageProps: { session, ...pageProps } }: AppProps) {
return (
<QueryClientProvider client={queryClient}>
<QuerySettingsProvider value={{ endpoint: '/api/model', fetch: myFetch }}>
<AppContent />
</QuerySettingsProvider>
</QueryClientProvider>
);
}

export default MyApp;

Using the Query Hooks​

Call the useClientQueries hook to get a root object to access CRUD hooks for all models. From there, using the hooks is pretty much the same as using ZenStackClient in backend code.

// replace "/react" with "/vue", "/svelte" as needed
import { useClientQueries } from '@zenstackhq/tanstack-query/react';
import { schema } from '~/zenstack/schema-lite.ts';

const client = useClientQueries(schema);

// `usersWithPosts` is typed `User & { posts: Post[] }`
const { data: usersWithPosts } = client.user.useFindMany({
include: { posts: true },
orderBy: { createdAt: 'desc' },
});

const createPost = client.post.useCreate();

function onCreate() {
createPost.mutate({ title: 'Some new post' });
}

The useClientQueries takes the schema as an argument, and it uses it for both type inference and runtime logic (e.g., automatic query invalidation). This may bring security concerns, because the schema object contains sensitive content like access policies. Using it in the frontend code will expose such information.

To mitigate the risk, you can pass the additional --lite option when running zen generate. With that flag on, the CLI will generate an additional "lite" schema object in schema-lite.ts with all attributes removed. The lite schema contains all information needed by the query hooks.

Optimistic Update​

Automatic Optimistic Update​

Optimistic update is a technique that allows you to update the data cache immediately when a mutation executes while waiting for the server response. It helps achieve a more responsive UI. TanStack Query provides the infrastructure for implementing it.

The ZenStack-generated mutation hooks allow you to opt-in to "automatic optimistic update" by passing the optimisticUpdate option when calling the hook. When the mutation executes, it analyzes the current queries in the cache and tries to find the ones that need to be updated. When the mutation settles (either succeeded or failed), the queries are invalidated to trigger a re-fetch.

Here's an example:

const { mutate: create } = useCreatePost({ optimisticUpdate: true });

function onCreatePost() {
create({ ... })
}

When mutate executes, if there are active queries like client.post.useFindMany(), the data of the mutation call will be optimistically inserted into the head of the query result.

Details of the optimistic behavior​

  • create mutation inserts item to the head of the query results of the corresponding useFindMany queries.
  • update mutation updates the item in the query results of useFindXXX queries and their nested reads by matching the item's ID.
  • upsert mutation first tries to update the item in the query results of useFindXXX queries and their nested reads by matching the item's ID. If the item is not found, it inserts the item to the head of the query results.
  • delete mutation removes the item from the query results of the corresponding useFindMany queries and sets null to useFindUnique and useFindFirst query results, by matching the item's ID.

Limitations​

  • The automatic optimistic update relies on ID matching. It only works for queries that select the ID field(s).
  • Non-entity-fetching queries like count, aggregate, and groupBy are not affected.
  • Infinite queries are not affected.
  • It doesn't respect filter conditions or access policies that potentially affect the queries under update. For example, for query client.post.useFindMany({ where: { published: true }}), when a non-published Post is created, it'll still be inserted into the query result.

Fine-Grained Optimistic Update​

Automatic optimistic update is convenient, but there might be cases where you want to explicitly control how the update happens. You can use the optimisticUpdateProvider callback to fully customize how each query cache entry should be optimistically updated. When the callback is set, it takes precedence over the automatic optimistic logic.

client.post.useCreate({
optimisticUpdateProvider: ({ queryModel, queryOperation, queryArgs, currentData, mutationArgs }) => {
return { kind: 'Update', data: ... /* computed result */ };
}
});

The callback is invoked for each query cache entry and receives the following arguments in a property bag:

  • queryModel: The model of the query, e.g., Post.
  • queryOperation: The operation of the query, e.g., findMany, count.
  • queryArgs: The arguments of the query, e.g., { where: { published: true } }.
  • currentData: The current cache data.
  • mutationArgs: The arguments of the mutation, e.g., { data: { title: 'My awesome post' } }.

It should return a result object with the following fields:

  • kind: The kind of the optimistic update.
    • Update: update the cache using the computed data
    • Skip: skip the update
    • ProceedDefault: use the default automatic optimistic behavior.
  • data: The computed data to update the cache with. Only used when kind is Update.

Opt-out​

By default, all queries opt into automatic optimistic update. You can opt-out on a per-query basis by passing false to the optimisticUpdate option.

const { data } = client.post.useFindMany(
{ where: { published: true } },
{ optimisticUpdate: false }
);

When a query opts out, it won't be updated by a mutation, even if the mutation is set to update optimistically.

Infinite Query​

The useFindMany hook has an "infinite" variant that helps you build pagination or infinitely scrolling UIs.

Here's a quick example of using infinite query to load a list of posts with infinite pagination. See TanStack Query documentation for more details.

/src/components/Posts.tsx
import { useClientQueries } from '@zenstackhq/tanstack-query/react';

// post list component with infinite loading
const Posts = () => {

const client = useClientQueries(schema);

const PAGE_SIZE = 10;

const fetchArgs = {
include: { author: true },
orderBy: { createdAt: 'desc' as const },
take: PAGE_SIZE,
};

const { data, fetchNextPage, hasNextPage } = client.post.useInfiniteFindMany(fetchArgs, {
getNextPageParam: (lastPage, pages) => {
if (lastPage.length < PAGE_SIZE) {
return undefined;
}
const fetched = pages.flatMap((item) => item).length;
return {
...fetchArgs,
skip: fetched,
};
},
});

return (
<>
<ul>
{data?.pages.map((posts, i) => (
<React.Fragment key={i}>
{posts?.map((post) => (
<li key={post.id}>
{post.title} by {post.author.email}
</li>
))}
</React.Fragment>
))}
</ul>
{hasNextPage && (
<button onClick={() => fetchNextPage()}>
Load more
</button>
)}
</>
);
};

Advanced Topics​

Query Invalidation​

The mutation hooks generated by ZenStack automatically invalidates the queries that are potentially affected by the changes. For example, if you create a Post, the client.post.useFindMany() query will be automatically invalidated when the mutation succeeds. Invalidation causes cache to be purged and fresh data to be refetched.

The automatic invalidation takes care of nested read, write, and delete cascading.

1. Nested Read

Nested reads are also subject to automatic invalidation. For example, if you create a Post, the query made by

client.user.useFindUnique({ where: { id: userId }, include: { posts: true } });

will be invalidated.

2. Nested Write

Similarly, nested writes also trigger automatic invalidation. For example, if you create a Post in a nested update to User like:

updateUser.mutate({ where: { id: userId }, posts: { create: { title: 'post1' } } });

The mutation will cause queries like client.post.useFindMany() to be invalidated.

3. Delete Cascade

In ZModel, relations can be configured to cascade delete, e.g.:

model User {
...
posts Post[]
}

model Post {
...
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
userId Int
}

When a User is deleted, the Post entities it owns will be deleted automatically. The generated hooks takes cascade delete into account. For example, if you delete a User, Post model will be considered as affected and queries like client.post.useFindMany() will be invalidated.

info

The automatic invalidation is enabled by default, and you can use the invalidateQueries option to opt-out and handle revalidation by yourself.

useCreatePost({ invalidateQueries: false });

Query Key​

Query keys serve as unique identifiers for organizing the query cache. The generated hooks use the following query key scheme:

['zenstack', model, operation, args, flags]

For example, the query key for

useFindUniqueUser({ where: { id: '1' } })

will be:

['zenstack', 'User', 'findUnique', { where: { id: '1' } }, { infinite: false }]

You can use the generated getQueryKey function to compute it.

The query hooks also return the query key as part of the result object.

const { data, queryKey } = useFindUniqueUser({ where: { id: '1' } });

Query Cancellation​

You can use TanStack Query's queryClient.cancelQueries API to cancel a query. The easiest way to do this is to use the queryKey returned by the query hook.

const queryClient = useQueryClient();
const { queryKey } = useFindUniqueUser({ where: { id: '1' } });

function onCancel() {
queryClient.cancelQueries({ queryKey, exact: true });
}

When a cancellation occurs, the query state is reset and the ongoing fetch call to the CRUD API is aborted.

Example​

The following live demo shows how to use the query hooks in a React SPA.

Click here to open an interactive playground.
src/App.tsx
import { useClientQueries } from '@zenstackhq/tanstack-query/react';
import { LoremIpsum } from 'lorem-ipsum';
import { schema } from './zenstack/schema-lite';

const lorem = new LoremIpsum({ wordsPerSentence: { min: 3, max: 5 } });

function App() {
const clientQueries = useClientQueries(schema);
const { data: users } = clientQueries.user.useFindMany();
const { data: posts } = clientQueries.post.useFindMany({
orderBy: { createdAt: 'desc' },
include: { author: true },
});
const createPost = clientQueries.post.useCreate();
const deletePost = clientQueries.post.useDelete();

const onCreatePost = () => {
if (!users) {
return;
}

// random title
const title = lorem.generateWords();

// random user as author
const forUser = users[Math.floor(Math.random() * users.length)];

createPost.mutate({
data: {
title,
authorId: forUser.id,
},
});
};

const onDeletePost = (postId: string) => {
deletePost.mutate({
where: { id: postId },
});
};

return (
<main>
<h1>My Awesome Blog</h1>

<button
onClick={onCreatePost}
className="btn"
>
New Post
</button>

<div>
<div>Current users</div>
<div className="users">
{users?.map((user) => (
<div
key={user.id}
className="user"
>
{user.email}
</div>
))}
</div>
</div>

<div className="posts">
{posts?.map((post) => (
<div key={post.id}>
<div className="post">
<div className="flex flex-col text-left">
<h2>{post.title}</h2>
<p className="author">by {post.author.name}</p>
</div>
<button
className="btn-link"
onClick={() =>
onDeletePost(post.id)
}
>
Delete
</button>
</div>
</div>
))}
</div>
</main>
);
}

export default App;
Comments
Feel free to ask questions, give feedback, or report issues.

Don't Spam


You can edit/delete your comments by going directly to the discussion, clicking on the 'comments' link below