T
TanStack2y ago
continuing-cyan

How to implement a useMutation call from table row onClick action?

Hello guys! I have implemented a datatable using the shadcn/ui datatable component. I'm struggling to figure out how to implement the row deletion action. I need the onClick to trigger a useMutation hook, but I can't figure out how to structure the code, specially where to place my hook call in the table code structure. My table is a "stock" shadcn/ui DataTable component:
<DataTable columns={columns} data={projectInvestmentsDetails} />
<DataTable columns={columns} data={projectInvestmentsDetails} />
In the row level I have two ids available that I need in order to delete the data
onClick={() =>
console.log(`${investment.id} - ${investment.projectId}`)
}
onClick={() =>
console.log(`${investment.id} - ${investment.projectId}`)
}
I need the onClick action in the row to call this useMutation for deleting the row data:
const queryClient = useQueryClient();
const { mutate: deleteProjectInvestment } = useMutation({
mutationFn: () => {
return axios.post(
`/api/project/${projectId}/investments/${investmentId}`
);
},
onError: (error) => {
toast.error("Error");
console.error(error);
},
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: [`project-${projectId}-investments`],
});

toast.success("Success");
},
});
const queryClient = useQueryClient();
const { mutate: deleteProjectInvestment } = useMutation({
mutationFn: () => {
return axios.post(
`/api/project/${projectId}/investments/${investmentId}`
);
},
onError: (error) => {
toast.error("Error");
console.error(error);
},
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: [`project-${projectId}-investments`],
});

toast.success("Success");
},
});
I tried several ways to implement this based on some posts I found, but none worked as intended. Have anyone done something like this before and can share some ideias? Thanks a lot!
1 Reply
continuing-cyan
continuing-cyanOP2y ago
I managed to to it by extracting the cell component and using the hook inside of it:
{
id: "actions",
cell: ({ row }) => <DataTableRowActions row={row} />,
},
{
id: "actions",
cell: ({ row }) => <DataTableRowActions row={row} />,
},

Did you find this page helpful?