import { authMutationKeys, authQueryKeys } from "@better-auth-ui/core" import { mutationOptions, type QueryClient, useMutation } from "@tanstack/react-query" import type { BetterFetchError } from "better-auth/react" import type { AuthClient } from "../../lib/auth-client" import { useSession } from "../../queries/auth/session-query" export type UnlinkAccountParams = Parameters< TAuthClient["unlinkAccount"] >[0] export type UnlinkAccountOptions = Omit< ReturnType>, "mutationKey" | "mutationFn" | "meta" > /** * Mutation options factory for unlinking a social provider from the current user. * * @param authClient - The Better Auth client. */ export function unlinkAccountOptions( authClient: TAuthClient ) { const mutationKey = authMutationKeys.unlinkAccount const mutationFn = (params: UnlinkAccountParams) => authClient.unlinkAccount({ ...params, fetchOptions: { ...params?.fetchOptions, throw: true } }) return mutationOptions< Awaited>, BetterFetchError, Parameters[0] >({ mutationKey, mutationFn }) } /** * Create a mutation for unlinking a social provider from the current user. * * On success, `MutationInvalidator` awaits invalidation of the linked * accounts list (see `meta.awaits`). * * @param authClient - The Better Auth client. * @param options - React Query options forwarded to `useMutation`. */ export function useUnlinkAccount( authClient: TAuthClient, options?: UnlinkAccountOptions, queryClient?: QueryClient ) { const { data: session } = useSession(authClient, undefined, queryClient) const userId = session?.user.id return useMutation( { ...unlinkAccountOptions(authClient), ...options, meta: { awaits: [authQueryKeys.listAccounts(userId)] } }, queryClient ) }