Reputation: 539
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
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:
useUtils()
:import { api } from '../trpc/react';
function MyComponent() {
const utils = api.useUtils();
utils.post.byId.invalidate({ id: 1 });
utils.post.invalidate();
utils.invalidate();
useMutation.onSuccess()
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
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
Reputation: 9
If you are using TRPC v10, you can do something like this:
utils.your.route.invalidate()
Upvotes: -2