T
TanStack2y ago
xenial-black

using hooks in columndef

This is a snippet of my columndef, it is the last column.
{
id: "actions",
cell: ({ row }) => {
const productId = row.original.id
const queryClient = useQueryClient() // can't use a hook in here

return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="w-8 h-8 p-0">
<span className="sr-only">Open menu</span>
<MoreHorizontal className="w-4 h-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<Link
to={`/products/${productId}`}
state={row.original}
>
<DropdownMenuItem>
Edit
</DropdownMenuItem>
</Link>
<DropdownMenuSeparator />
<DropdownMenuItem
className="text-destructive"
onClick={() => axios.delete(
"http://localhost:3001/api/products/delete",
{data: {id: productId}}
).then(res => {
if (res.status === 200) {
toast("deleted")
queryClient.invalidateQueries('products')
}
})}
>Delete</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)
},
},
{
id: "actions",
cell: ({ row }) => {
const productId = row.original.id
const queryClient = useQueryClient() // can't use a hook in here

return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="w-8 h-8 p-0">
<span className="sr-only">Open menu</span>
<MoreHorizontal className="w-4 h-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<Link
to={`/products/${productId}`}
state={row.original}
>
<DropdownMenuItem>
Edit
</DropdownMenuItem>
</Link>
<DropdownMenuSeparator />
<DropdownMenuItem
className="text-destructive"
onClick={() => axios.delete(
"http://localhost:3001/api/products/delete",
{data: {id: productId}}
).then(res => {
if (res.status === 200) {
toast("deleted")
queryClient.invalidateQueries('products')
}
})}
>Delete</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)
},
},
I want to invalidate the query when the action is complete. But I can't use the useQueryClient hook in here. Is there a proper way to do this in columndef?
3 Replies
deep-jade
deep-jade2y ago
Create a custom component
unwilling-turquoise
unwilling-turquoise2y ago
Yes - a custom component. Store the dynamic data you want to use within your cell render, then create your dom structure and DropdownMenu wrapper within your custom component.
xenial-black
xenial-blackOP2y ago
that make sense. Thanks!

Did you find this page helpful?