3

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,
    })
  }
Arpit
  • 467
  • 1
  • 8
  • 18

2 Answers2

6

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 
    },
  });

  // [...]
}
Rahul Chandra
  • 483
  • 7
  • 15
  • onSuccess() is deprecated, any clue on how to do it without using deprecated functions? – Daniel Aviv Jul 07 '23 at 20:48
  • @DanielAviv `onSuccess` is not deprecated in `useMutation` but in `useQuery`. See https://tkdodo.eu/blog/breaking-react-querys-api-on-purpose . It is specifically mentioned. – IcyIcicle Aug 09 '23 at 16:48
-1

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

utils.your.route.invalidate()
Vitor G
  • 11
  • 2