Trongar
Trongar15mo ago

Optimizing Data Refresh with trpc in React/Nextjs? Is there a more efficient way?

I'm working on a Nextjs project using trpc, and I've noticed that I'm repeating the same code for data refetching after mutations (add, update, delete) using trpc mutations. Is there a more efficient or DRY (Don't Repeat Yourself) approach to handle data refreshing after mutations with trpc in React? I'd appreciate any suggestions or best practices to optimize this process.
const addTask = trpcClient.tasks.addTask.useMutation({
onSettled: () => {
getTasks.refetch();
},
});
const setDone = trpcClient.tasks.setTaskStatus.useMutation({
onSettled: () => {
getTasks.refetch();
},
});

const deleteTask = trpcClient.tasks.deleteTask.useMutation({
onSettled: () => {
getTasks.refetch();
},
});
const addTask = trpcClient.tasks.addTask.useMutation({
onSettled: () => {
getTasks.refetch();
},
});
const setDone = trpcClient.tasks.setTaskStatus.useMutation({
onSettled: () => {
getTasks.refetch();
},
});

const deleteTask = trpcClient.tasks.deleteTask.useMutation({
onSettled: () => {
getTasks.refetch();
},
});
2 Replies
jthrilly
jthrilly15mo ago
There's the thermonuclear option: https://trpc.io/docs/client/react/useContext#invalidate-full-cache-on-every-mutation But yeah, I'm also interested in this...
useContext | tRPC
useContext is a hook that gives you access to helpers that let you manage the cached data of the queries you execute via @trpc/react-query. These helpers are actually thin wrappers around @tanstack/react-query's queryClient methods. If you want more in-depth information about options and usage patterns for useContext helpers than what we provide...
Trongar
TrongarOP15mo ago
but how could it be, i don´t get it i want to make somthing like
const {addTask, deleteTask, setStatus} = trpcClient.tasks.(...).useMutation({
onSettled: () => {
getTasks.refetch();
},
});
const {addTask, deleteTask, setStatus} = trpcClient.tasks.(...).useMutation({
onSettled: () => {
getTasks.refetch();
},
});