Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

1.8 KB
Raw Blame
import type { MeResponse, MeUpdateParams } from '@spree/admin-sdk'
import { adminClient, useResourceKey, useResourceMutation } from '@spree/dashboard-core'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'

/**
 * @param enabled Defer the request until it's needed. The edit-profile dialog
 *   is mounted on every store page but only fetches once it opens.
 */
export function useProfile(enabled = true) {
  return useQuery({
    queryKey: useResourceKey('profile'),
    queryFn: () => adminClient.me.get(),
    enabled,
  })
}

export function useUpdateProfile() {
  const { t } = useTranslation()
  const queryClient = useQueryClient()
  const profileKey = useResourceKey('profile')

  return useResourceMutation<MeResponse, Error, MeUpdateParams>({
    mutationFn: (params) => adminClient.me.update(params),
    // The signed-in admin is also a row on the staff page, so their own name
    // and avatar there go stale on a self-edit unless that list is refetched.
    invalidate: [['profile'], ['staff']],
    successMessage: false, // the dialog toasts success itself
    // Field-level 422s never toast — the dialog shows them inline — so this
    // covers everything else: a refusal, a server error, a lost connection.
    errorMessage: t('admin.errors.failed_to_update_profile'),
    // Write the response into the cache instead of leaning on the invalidation
    // alone. The dialog disables the profile query while closed, and an
    // invalidated query with no enabled observer goes stale without refetching
    // — so a reopen would otherwise render the pre-save profile (flashing back
    // an avatar the admin just removed).
    onSuccess: (updated) => queryClient.setQueryData(profileKey, updated),
  })
}