Skip to content

Instantly share code, notes, and snippets.

@coder054
Created October 4, 2022 02:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coder054/8e6f08032c28919f1b9efb4087a002f7 to your computer and use it in GitHub Desktop.
Save coder054/8e6f08032c28919f1b9efb4087a002f7 to your computer and use it in GitHub Desktop.
react query mutation
import { apiClient, REACT_QUERY_KEYS } from '@/config'
import { getErrorMessage } from '@/utils/utils'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useRouter } from 'next/router'
import { toast } from 'react-toastify'
export const useDeleteDevice = ({
isOnDeviceListPage,
callbackOnSuccess,
}: {
isOnDeviceListPage: boolean
callbackOnSuccess: Function
}) => {
const queryClient = useQueryClient()
const router = useRouter()
const mutation = useMutation(
async (id: string) => {
const { data } = await apiClient.delete(`/device/${id}`)
return data.success
},
{
onSuccess: () => {
toast.success('Device deleted successfully')
if (isOnDeviceListPage) {
queryClient.invalidateQueries([REACT_QUERY_KEYS.LIST_DEVICE])
} else {
router.push('/device')
}
callbackOnSuccess()
},
onError: (error: any) => {
toast.error(getErrorMessage(error))
},
}
)
return mutation
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment