Arpit
Arpit

Reputation: 539

How do I invalidate queries and fetch latest data in TRPC?

I am simply trying to get latest data from the server after performing a mutation. My code looks something like this:

  const utils = trpc.useContext()
  const markAsUnreadMutation = trpc.useMutation(['update-mark-as-unread'], {
    onSuccess() {
      utils.invalidateQueries() //THIS IS NOT WORKING!
    },
    onError(data) {
      toast({
        type: 'error',
        message: data.message,
      })
    },
  })

  function markAsUnread(isUnread: boolean) {
    markAsUnreadMutation.mutate({
      id: parseInt(channel.id),
      markAsUnread: isUnread,
    })
  }

Upvotes: 3

Views: 12442

Answers (3)

Daryn
Daryn

Reputation: 5107

(As noted in the comments, should now use useUtils() instead of useContext())

The tRPC useUtils() docs Query Invalidation section gives examples of various levels of invalidation:

First, useUtils():

import { api } from '../trpc/react';

function MyComponent() {
  const utils = api.useUtils();

Then...

  1. Invalidate a single query
    utils.post.byId.invalidate({ id: 1 });
  1. Invalidate all “post” queries
    utils.post.invalidate();
  1. Invalidate all queries on the router
    utils.invalidate();
  1. Automatically invalidate the whole cache on every mutation.

For the OP’s question:

There’s a bit too much react-query going on in the OP’s code. tRPC provides helper wrappers around react-query/tanstack-query, including the invalidate helper for queryClient.invalidateQueries. These tRPC helpers take care of passing the react-query query key, derived from the tRPC endpoint. (Which is why the OP should not need to pass the ['update-mark-as-unread'] query key). useUtils().[ROUTE...].invalidate() is one of those wrappers

Upvotes: 1

Rahul Chandra
Rahul Chandra

Reputation: 583

Invalidating a single query

You can invalidate a query relating to a single procedure and even filter based on the input passed to it to prevent unnecessary calls to the back end.

import { trpc } from '../utils/trpc';

function MyComponent() {
  const utils = trpc.useContext();

  const mutation = trpc.post.edit.useMutation({
    onSuccess(input) {
      utils.post.all.invalidate();
      utils.post.byId.invalidate({ id: input.id }); // Will not invalidate queries for other id's 👍
    },
  });

  // [...]
}

Upvotes: 12

Vitor G
Vitor G

Reputation: 9

If you are using TRPC v10, you can do something like this:

utils.your.route.invalidate()

Upvotes: -2

Related Questions