edit
edit
TtRPC
Created by edit on 5/13/2025 in #❓-help
Optimistic updates using tRPC 11 with TanStack React Query 5
I found a similar post in here but it didn't have info that helped so I'm making this one. I have a tRPC query + mutation setup in a single component that looks like this:
const queryClient = useQueryClient();
const trpc = useTRPC();

const queryOptions = trpc.getTodaysMindsetMatters.queryOptions({ authToken });
const { data: mindsetMatters, isPending } = useQuery(queryOptions);
const queryKey = trpc.getTodaysMindsetMatters.queryKey();

const mutationOptions = trpc.submitMindsetMattersFeedback.mutationOptions({
onSettled: () => queryClient.invalidateQueries({ queryKey })
});

const { mutate } = useMutation(mutationOptions);

const onFeedbackPositive = async () => {
mutate({ authToken, sentiment: 1 });
};

const onFeedbackNegative = async () => {
mutate({ authToken, sentiment: -1 });
};
const queryClient = useQueryClient();
const trpc = useTRPC();

const queryOptions = trpc.getTodaysMindsetMatters.queryOptions({ authToken });
const { data: mindsetMatters, isPending } = useQuery(queryOptions);
const queryKey = trpc.getTodaysMindsetMatters.queryKey();

const mutationOptions = trpc.submitMindsetMattersFeedback.mutationOptions({
onSettled: () => queryClient.invalidateQueries({ queryKey })
});

const { mutate } = useMutation(mutationOptions);

const onFeedbackPositive = async () => {
mutate({ authToken, sentiment: 1 });
};

const onFeedbackNegative = async () => {
mutate({ authToken, sentiment: -1 });
};
It works fine but I'd like to do an optimistic update to show the post-mutation state immediately. I read the TanStack docs for this but I don't understand how either of the methods would work with tRPC. Could anyone provide some guidance? Thanks in advance!
4 replies