Skip to content

Instantly share code, notes, and snippets.

@edoves
Created October 30, 2024 15:07
Show Gist options
  • Select an option

  • Save edoves/b758f48aceac444b0bf036422db4bccd to your computer and use it in GitHub Desktop.

Select an option

Save edoves/b758f48aceac444b0bf036422db4bccd to your computer and use it in GitHub Desktop.
TanStack Query Code samle

useMutation use for editing adding updatting or deleting data in the database

useMutationHook.js

import { useMutation, useQueryClient } from '@tanstack/react-query'
import { addMemberPayment as addMemberPaymentApi } from 'api/services'

function useHookName() {
  const queryClient = useQueryClient()
  const { mutate: addMemberPayment, isPending } = useMutation({
    mutationFn: (data) => addMemberPaymentApi(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['loans'] }) //refecthing the data when something has change or update
    },
    onError: {},
    onMutate: {},
  })

  return { addMemberPayment, isPending }
}

export default useHookName

useQuery use for fetching data

useQueryHook.js

import { useQuery } from '@tanstack/react-query'
import { getLoanByMemberId } from 'api/services'

function useQueryHook(id) {
  const { data: loans, isLoading } = useQuery({
    queryKey: ['loans', id],
    queryFn: () => getLoanByMemberId(id),
  })

  return { loans, isLoading }
}

export default useQueryHook
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment