Skip to content

[Feature Request] getQueryKey() function to help with optimistic updates in tanstack-Query #697

@ErikDakoda

Description

@ErikDakoda

Background: In tanstack-query the query key is required for queryClient.setQueryData() to implement optimistic updates.

Currently a query key is a triad of :[ModelName, QueryURL, QueryArgs], so for example for useUserFindUnique, the key will be: ['User', 'http://.../user/findUnique%60, queryArgs]. Computing it manually is not recommended, as it may change in the future.

Here is how this may work:

import { getQueryKey } from "@zenstackhq/tanstack-query";

const queryClient = useQueryClient();

// get query key for the current post
const postKey = getQueryKey('Post', 'findUnique', { where: { id: postId } });

const updatePost = useUpdatePost({
  onMutate: (newData) => {
    const previous = queryClient.getQueryData(postKey);
    // optimistically update the current post
    queryClient.setQueryData(postKey, (old) => ({...old, ...newData.data});
    return { previous };
  },
  onError: (err, newData, context) => {
    queryClient.setQueryData(postKey, context.previous);
  }
});

const onUpdate = () => {
  updatePost.mutate(...);
};

It would be great to also have a getQueryKeys() function that accepts partial parameters and returns an array of matches. For example getQueryKeys({ modelName: 'Post' }) for all Post queries or getQueryKeys({ queryArgs: { select: { posts: true } } }) for all queries with a relation to posts.

It would also be nice if the result object returned by query functions like findUnique would also include the query key. Of course, if you are just passing the result returned by tanstack-query you may not want to mutate that object.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions