Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

1.3 KB
Raw Blame
import type { UserIdentity } from '@supabase/supabase-js'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'

import { profileKeys } from './keys'
import { auth } from '@/lib/gotrue'
import { UseCustomMutationOptions } from '@/types'

const unlinkIdentity = async (identity: UserIdentity) => {
  const { error, data } = await auth.unlinkIdentity(identity)

  if (error) throw error
  return data
}

type UnlinkIdentityResponse = any
type UnlinkIdentityError = any

export const useUnlinkIdentityMutation = ({
  onSuccess,
  onError,
  ...options
}: Omit<
  UseCustomMutationOptions<UnlinkIdentityResponse, UnlinkIdentityError, UserIdentity>,
  'mutationFn'
> = {}) => {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (vars) => unlinkIdentity(vars),
    async onSuccess(data, variables, context) {
      await Promise.all([
        auth.refreshSession(),
        queryClient.invalidateQueries({ queryKey: profileKeys.identities() }),
      ])
      await onSuccess?.(data, variables, context)
    },
    async onError(data, variables, context) {
      if (onError === undefined) {
        toast.error(`Failed to unlink identity: ${data.message}`)
      } else {
        onError(data, variables, context)
      }
    },
    ...options,
  })
}