Files
supabase/apps/studio/data/profile/profile-update-mutation.ts
a1f2e50068 feat(profile): add self-serve editing of username and primary email (#38042)
* feat(profile): add self-serve editing of username and primary email

Users can now update `username` and choose a `primary_email` directly in the
Dashboard profile editor.

Changes:
- Add `username` and `primary_email` fields to the profile form.
- Introduce `Select_Shadcn_` dropdown listing the user's identities
  (via `useProfileIdentitiesQuery`) for selecting a primary email.
- Default `primary_email` selection is derived from the current profile.
- Extend form submission to patch `username` and `primary_email` to the
  profile API.
- Wire zod schema and react-hook-form defaults for new fields.

* chore: remove unused variable

* fix: disable username & primary_email modification for SSO users

* Small refactors

* Remove hard code

* Refactor to use FormItemLayout

* chore: add descriptions for primary_email and username

* chore: fix format and lint error

* chore: fix lint error

* Use identities to derive user dropdown profile image, and remove profile image from useProfile hook

---------

Co-authored-by: Chris Stockton <chris.stockton@supabase.io>
Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
2025-08-25 07:30:57 -07:00

64 lines
1.6 KiB
TypeScript

import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { handleError, patch } from 'data/fetchers'
import type { ResponseError } from 'types'
import { profileKeys } from './keys'
export type ProfileUpdateVariables = {
firstName: string
lastName: string
username: string
primaryEmail: string
}
export async function updateProfile({
firstName,
lastName,
username,
primaryEmail,
}: ProfileUpdateVariables) {
const { data, error } = await patch('/platform/profile', {
body: {
first_name: firstName,
last_name: lastName,
username: username,
primary_email: primaryEmail,
},
})
if (error) handleError(error)
return data
}
type ProfileUpdateData = Awaited<ReturnType<typeof updateProfile>>
export const useProfileUpdateMutation = ({
onSuccess,
onError,
...options
}: Omit<
UseMutationOptions<ProfileUpdateData, ResponseError, ProfileUpdateVariables>,
'mutationFn'
> = {}) => {
const queryClient = useQueryClient()
return useMutation<ProfileUpdateData, ResponseError, ProfileUpdateVariables>(
(vars) => updateProfile(vars),
{
async onSuccess(data, variables, context) {
await queryClient.invalidateQueries(profileKeys.profile())
await onSuccess?.(data, variables, context)
},
async onError(data, variables, context) {
if (onError === undefined) {
toast.error(`Failed to create profile: ${data.message}`)
} else {
onError(data, variables, context)
}
},
...options,
}
)
}