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.

Dashboard: unify store-scoped query keys across hooks, tables, mutations

Damian Legawiec842e52e07761
diff --git a/packages/dashboard-core/src/components/resource-table.tsx b/packages/dashboard-core/src/components/resource-table.tsx
index 4f4892fa5e..05104dcfa7 100644
--- a/packages/dashboard-core/src/components/resource-table.tsx
+++ b/packages/dashboard-core/src/components/resource-table.tsx
@@ -52,6 +52,7 @@ import { useTranslation } from 'react-i18next'
import { z } from 'zod/v4'
import { useAuth } from '../hooks/use-auth'
import { filtersToRansack } from '../lib/filters-to-ransack'
+import { withStoreScope } from '../lib/query-keys'
import {
type ColumnDef,
type FilterRule,
@@ -60,6 +61,7 @@ import {
getTable,
type SortOption,
} from '../lib/table-registry'
+import { useStore } from '../providers/store-provider'
import { type BulkAction, BulkActionBar } from './bulk-action-bar'
import { TableToolbar } from './table-toolbar'
@@ -126,8 +128,14 @@ export interface ResourceActionsContext {
interface ResourceTableProps<T> {
/** Registry key (e.g., 'products') */
tableKey: string
- /** TanStack Query key prefix (e.g., 'products') */
- queryKey: string
+ /**
+ * TanStack Query key prefix. The table auto-injects the current storeId so
+ * mutation hooks that invalidate `['<key>', storeId]` always match — pages
+ * never need to thread storeId through themselves. A plain string is
+ * shorthand for `[string]`; pass an array to add further scope (e.g.
+ * `[webhookDeliveriesTableKey(endpointId)]`).
+ */
+ queryKey: string | readonly unknown[]
/** Function that calls the SDK to fetch data */
queryFn: (params: Record<string, unknown>) => Promise<{ data: T[]; meta: PaginationMeta }>
/** Current search params from the route */
@@ -237,8 +245,19 @@ export function ResourceTable<T extends Record<string, any>>({
// Build API params
const sortString = dir === 'desc' ? `-${sort}` : sort
+ const { storeId } = useStore()
+ // Auto-inject storeId so every list query — and the matching mutation
+ // invalidation — is store-scoped without each page re-implementing it.
+ // Goes through +withStoreScope+ so the slot ordering matches +useResourceKey+
+ // and +useResourceMutation+'s invalidations (storeId at position 1).
+ const userPrefix = Array.isArray(queryKey) ? queryKey : [queryKey]
+ const queryKeyPrefix = withStoreScope(userPrefix, storeId)
+
const { data, isLoading } = useQuery({
- queryKey: [queryKey, { page, limit, sort: sortString, search: deferredSearch, filters }],
+ queryKey: [
+ ...queryKeyPrefix,
+ { page, limit, sort: sortString, search: deferredSearch, filters },
+ ],
queryFn: () => {
const params: Record<string, unknown> = {
page,
@@ -574,7 +593,7 @@ export function ResourceTable<T extends Record<string, any>>({
onClear={() => setSelectedIds(new Set())}
onDone={() => {
setSelectedIds(new Set())
- queryClient.invalidateQueries({ queryKey: [queryKey] })
+ queryClient.invalidateQueries({ queryKey: queryKeyPrefix })
}}
/>
)}
diff --git a/packages/dashboard-core/src/hooks/use-resource-mutation.ts b/packages/dashboard-core/src/hooks/use-resource-mutation.ts
index 69ea433667..732188dff4 100644
--- a/packages/dashboard-core/src/hooks/use-resource-mutation.ts
+++ b/packages/dashboard-core/src/hooks/use-resource-mutation.ts
@@ -6,10 +6,17 @@ import {
useQueryClient,
} from '@tanstack/react-query'
import { toast } from 'sonner'
+import { withStoreScope } from '../lib/query-keys'
+import { useStore } from '../providers/store-provider'
interface UseResourceMutationOptions<TData, TError, TVariables>
extends Omit<UseMutationOptions<TData, TError, TVariables>, 'onSuccess' | 'onError'> {
- /** Query keys to invalidate after success. Wrap singletons: `[orderQueryKey(id)]`. */
+ /**
+ * Query keys to invalidate after success. Pass logical keys without
+ * storeId (e.g. `[['channels'], ['channels', id]]`) — the hook injects the
+ * current storeId at position 1 automatically so invalidation matches the
+ * store-scoped keys used by `ResourceTable` and other queries.
+ */
invalidate?: QueryKey[]
/** Toast on success. Pass `false` to disable. Default `'Saved'`. */
successMessage?: string | false
@@ -47,6 +54,7 @@ export function useResourceMutation<TData = unknown, TError = Error, TVariables
options: UseResourceMutationOptions<TData, TError, TVariables>,
) {
const queryClient = useQueryClient()
+ const { storeId } = useStore()
const {
invalidate,
successMessage = 'Saved',
@@ -61,7 +69,7 @@ export function useResourceMutation<TData = unknown, TError = Error, TVariables
onSuccess: (data, variables, onMutateResult, ctx) => {
if (invalidate) {
for (const key of invalidate) {
- queryClient.invalidateQueries({ queryKey: key })
+ queryClient.invalidateQueries({ queryKey: withStoreScope(key, storeId) })
}
}
if (successMessage !== false) {
diff --git a/packages/dashboard-core/src/index.ts b/packages/dashboard-core/src/index.ts
index 17eaa59a9d..9495b1d724 100644
--- a/packages/dashboard-core/src/index.ts
+++ b/packages/dashboard-core/src/index.ts
@@ -66,6 +66,7 @@ export * from './lib/i18n'
export * from './lib/nav-registry'
export * from './lib/permissions'
export * from './lib/query-client'
+export * from './lib/query-keys'
export * from './lib/settings-nav-registry'
export * from './lib/slot-registry'
export * from './lib/table-registry'
diff --git a/packages/dashboard-core/src/lib/query-keys.ts b/packages/dashboard-core/src/lib/query-keys.ts
new file mode 100644
index 0000000000..693a015c16
--- /dev/null
+++ b/packages/dashboard-core/src/lib/query-keys.ts
@@ -0,0 +1,69 @@
+import type { QueryKey } from '@tanstack/react-query'
+import { useCallback } from 'react'
+import { useStore } from '../providers/store-provider'
+
+/**
+ * Canonical TanStack query-key shape for every dashboard resource:
+ *
+ * [resource, storeId, ...rest]
+ *
+ * Use `useResourceKey` (the hook) from inside React components to build
+ * store-scoped keys — it reads `storeId` from `<StoreProvider>` so callers
+ * never spell it themselves:
+ *
+ * useQuery({ queryKey: useResourceKey('channels', id), ... })
+ *
+ * The bare `resourceKey()` helper is the same builder without the storeId
+ * dependency — keep it for non-hook contexts (tests, build-time defaults).
+ *
+ * Lists: `useResourceKey('channels')`
+ * Singletons: `useResourceKey('channels', id)`
+ * Nested: `useResourceKey('products', productId, 'variants')`
+ *
+ * For invalidation inside `useResourceMutation`, the storeId is auto-injected
+ * — pass the logical key without it:
+ *
+ * invalidate: [['channels'], ['channels', id]]
+ */
+export function resourceKey(resource: string, ...rest: ReadonlyArray<unknown>): QueryKey {
+ return [resource, ...rest]
+}
+
+/**
+ * Hook variant of `resourceKey` that auto-injects the current `storeId` from
+ * `<StoreProvider>`. The default way to build query keys in dashboard hooks.
+ */
+export function useResourceKey(resource: string, ...rest: ReadonlyArray<unknown>): QueryKey {
+ const { storeId } = useStore()
+ return [resource, storeId, ...rest]
+}
+
+/**
+ * Returns a stable closure that builds store-scoped query keys. Use this when
+ * the key parts (typically an id) are only known later — e.g. inside a
+ * mutation's `onSuccess` where `variables.id` is per-call.
+ *
+ * const buildKey = useResourceKeyBuilder()
+ * return useResourceMutation({
+ * onSuccess: (_data, id) =>
+ * queryClient.removeQueries({ queryKey: buildKey('channels', id) }),
+ * })
+ */
+export function useResourceKeyBuilder() {
+ const { storeId } = useStore()
+ return useCallback(
+ (resource: string, ...rest: ReadonlyArray<unknown>): QueryKey => [resource, storeId, ...rest],
+ [storeId],
+ )
+}
+
+/**
+ * Inject `storeId` at position 1 of a query key, leaving the resource name at
+ * position 0 and any further scope after it. Idempotent — if the storeId is
+ * already at position 1, returns the input unchanged.
+ */
+export function withStoreScope(key: QueryKey, storeId: string): QueryKey {
+ if (!Array.isArray(key) || key.length === 0) return key
+ if (key[1] === storeId) return key
+ return [key[0], storeId, ...key.slice(1)]
+}
diff --git a/packages/dashboard/src/components/spree/bulk-price-editor/bulk-price-editor.tsx b/packages/dashboard/src/components/spree/bulk-price-editor/bulk-price-editor.tsx
index 54775a2c7e..cba30176d8 100644
--- a/packages/dashboard/src/components/spree/bulk-price-editor/bulk-price-editor.tsx
+++ b/packages/dashboard/src/components/spree/bulk-price-editor/bulk-price-editor.tsx
@@ -1,5 +1,5 @@
import type { PriceBulkUpsertRow } from '@spree/admin-sdk'
-import { adminClient } from '@spree/dashboard-core'
+import { adminClient, useResourceKey } from '@spree/dashboard-core'
import {
Button,
DataGrid,
@@ -146,10 +146,13 @@ export function BulkPriceEditor({
)
const { data, isLoading } = useQuery({
- queryKey: [
- 'prices',
- { priceListId: priceListId ?? null, currency, filter: filterKey, page, q: deferredSearch },
- ],
+ queryKey: useResourceKey('prices', {
+ priceListId: priceListId ?? null,
+ currency,
+ filter: filterKey,
+ page,
+ q: deferredSearch,
+ }),
queryFn: () =>
adminClient.prices.list({
// Caller-supplied predicates first, then the editor's own — the
diff --git a/packages/dashboard/src/hooks/use-allowed-origins.ts b/packages/dashboard/src/hooks/use-allowed-origins.ts
index 3fd1e68baa..596729e1c6 100644
--- a/packages/dashboard/src/hooks/use-allowed-origins.ts
+++ b/packages/dashboard/src/hooks/use-allowed-origins.ts
@@ -3,18 +3,17 @@ import type {
AllowedOriginCreateParams,
AllowedOriginUpdateParams,
} from '@spree/admin-sdk'
-import { adminClient, useResourceMutation } from '@spree/dashboard-core'
+import {
+ adminClient,
+ useResourceKey,
+ useResourceKeyBuilder,
+ useResourceMutation,
+} from '@spree/dashboard-core'
import { useQuery, useQueryClient } from '@tanstack/react-query'
-export const allowedOriginsQueryKey = ['allowed-origins'] as const
-
-export function allowedOriginQueryKey(id: string) {
- return ['allowed-origins', id] as const
-}
-
export function useAllowedOrigin(id: string | undefined) {
return useQuery({
- queryKey: id ? allowedOriginQueryKey(id) : ['allowed-origins', 'noop'],
+ queryKey: useResourceKey('allowed-origins', id ?? 'noop'),
queryFn: () => adminClient.allowedOrigins.get(id as string),
enabled: !!id,
})
@@ -23,7 +22,7 @@ export function useAllowedOrigin(id: string | undefined) {
export function useCreateAllowedOrigin() {
return useResourceMutation<AllowedOrigin, Error, AllowedOriginCreateParams>({
mutationFn: (params) => adminClient.allowedOrigins.create(params),
- invalidate: [allowedOriginsQueryKey],
+ invalidate: [['allowed-origins']],
successMessage: 'Allowed origin added',
errorMessage: 'Failed to add allowed origin',
})
@@ -32,7 +31,7 @@ export function useCreateAllowedOrigin() {
export function useUpdateAllowedOrigin(id: string) {
return useResourceMutation<AllowedOrigin, Error, AllowedOriginUpdateParams>({
mutationFn: (params) => adminClient.allowedOrigins.update(id, params),
- invalidate: [allowedOriginsQueryKey, allowedOriginQueryKey(id)],
+ invalidate: [['allowed-origins'], ['allowed-origins', id]],
successMessage: 'Allowed origin updated',
errorMessage: 'Failed to update allowed origin',
})
@@ -40,14 +39,15 @@ export function useUpdateAllowedOrigin(id: string) {
export function useDeleteAllowedOrigin() {
const queryClient = useQueryClient()
+ const buildKey = useResourceKeyBuilder()
return useResourceMutation<void, Error, string>({
mutationFn: (id) => adminClient.allowedOrigins.delete(id),
- invalidate: [allowedOriginsQueryKey],
+ invalidate: [['allowed-origins']],
successMessage: 'Allowed origin removed',
errorMessage: 'Failed to remove allowed origin',
onSuccess: (_data, id) => {
- queryClient.removeQueries({ queryKey: allowedOriginQueryKey(id) })
+ queryClient.removeQueries({ queryKey: buildKey('allowed-origins', id) })
},
})
}
diff --git a/packages/dashboard/src/hooks/use-api-keys.ts b/packages/dashboard/src/hooks/use-api-keys.ts
index 240cc2aa9e..2f42c2e2e7 100644
--- a/packages/dashboard/src/hooks/use-api-keys.ts
+++ b/packages/dashboard/src/hooks/use-api-keys.ts
@@ -1,42 +1,37 @@
import type { ApiKey, ApiKeyCreateParams } from '@spree/admin-sdk'
-import { adminClient } from '@spree/dashboard-core'
-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
-
-const API_KEYS_KEY = ['api-keys'] as const
+import { adminClient, useResourceKey, useResourceMutation } from '@spree/dashboard-core'
+import { useQuery } from '@tanstack/react-query'
export function useApiKeys() {
return useQuery({
- queryKey: API_KEYS_KEY,
+ queryKey: useResourceKey('api-keys'),
queryFn: () => adminClient.apiKeys.list({ limit: 100 }),
})
}
export function useCreateApiKey() {
- const qc = useQueryClient()
- return useMutation({
- mutationFn: (params: ApiKeyCreateParams) => adminClient.apiKeys.create(params),
- onSuccess: () => {
- qc.invalidateQueries({ queryKey: API_KEYS_KEY })
- },
+ return useResourceMutation<ApiKey, Error, ApiKeyCreateParams>({
+ mutationFn: (params) => adminClient.apiKeys.create(params),
+ invalidate: [['api-keys']],
+ successMessage: false,
+ errorMessage: false,
})
}
export function useRevokeApiKey() {
- const qc = useQueryClient()
- return useMutation<ApiKey, Error, string>({
- mutationFn: (id: string) => adminClient.apiKeys.revoke(id),
- onSuccess: () => {
- qc.invalidateQueries({ queryKey: API_KEYS_KEY })
- },
+ return useResourceMutation<ApiKey, Error, string>({
+ mutationFn: (id) => adminClient.apiKeys.revoke(id),
+ invalidate: [['api-keys']],
+ successMessage: false,
+ errorMessage: false,
})
}
export function useDeleteApiKey() {
- const qc = useQueryClient()
- return useMutation({
- mutationFn: (id: string) => adminClient.apiKeys.delete(id),
- onSuccess: () => {
- qc.invalidateQueries({ queryKey: API_KEYS_KEY })
- },
+ return useResourceMutation<void, Error, string>({
+ mutationFn: (id) => adminClient.apiKeys.delete(id),
+ invalidate: [['api-keys']],
+ successMessage: false,
+ errorMessage: false,
})
}
diff --git a/packages/dashboard/src/hooks/use-categories.ts b/packages/dashboard/src/hooks/use-categories.ts
index 97cd0e4238..9e713ea4c3 100644
--- a/packages/dashboard/src/hooks/use-categories.ts
+++ b/packages/dashboard/src/hooks/use-categories.ts
@@ -1,11 +1,11 @@
import type { Category } from '@spree/admin-sdk'
-import { adminClient } from '@spree/dashboard-core'
+import { adminClient, useResourceKey } from '@spree/dashboard-core'
import { useQuery } from '@tanstack/react-query'
import i18n from 'i18next'
export function useCategories() {
return useQuery({
- queryKey: ['categories'],
+ queryKey: useResourceKey('categories'),
queryFn: () => adminClient.categories.list({ limit: 100 }),
staleTime: 1000 * 60 * 5,
})
diff --git a/packages/dashboard/src/hooks/use-channels.ts b/packages/dashboard/src/hooks/use-channels.ts
index 00f6c01121..e8fabfbb88 100644
--- a/packages/dashboard/src/hooks/use-channels.ts
+++ b/packages/dashboard/src/hooks/use-channels.ts
@@ -1,20 +1,13 @@
import type { Channel, ChannelCreateParams, ChannelUpdateParams } from '@spree/admin-sdk'
-import { adminClient, useResourceMutation, useStore } from '@spree/dashboard-core'
+import {
+ adminClient,
+ useResourceKey,
+ useResourceKeyBuilder,
+ useResourceMutation,
+} from '@spree/dashboard-core'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import i18n from 'i18next'
-// Channels are store-scoped on the backend (`for_store(current_store)`), so
-// query keys MUST include the storeId — otherwise switching stores within
-// the staleTime window serves the previous store's channels. The hooks read
-// storeId from <StoreProvider> at call time.
-export function channelsQueryKey(storeId: string) {
- return ['channels', storeId] as const
-}
-
-export function channelQueryKey(storeId: string, id: string) {
- return ['channels', storeId, id] as const
-}
-
interface UseChannelsParams {
page?: number
limit?: number
@@ -22,38 +15,34 @@ interface UseChannelsParams {
}
export function useChannels({ page = 1, limit = 100, expand }: UseChannelsParams = {}) {
- const { storeId } = useStore()
return useQuery({
- queryKey: [...channelsQueryKey(storeId), { page, limit, expand: expand?.join(',') ?? '' }],
+ queryKey: useResourceKey('channels', { page, limit, expand: expand?.join(',') ?? '' }),
queryFn: () => adminClient.channels.list({ page, limit, ...(expand ? { expand } : {}) }),
staleTime: 1000 * 60 * 5,
})
}
export function useChannel(id: string | undefined) {
- const { storeId } = useStore()
return useQuery({
- queryKey: id ? channelQueryKey(storeId, id) : ['channels', storeId, 'noop'],
+ queryKey: useResourceKey('channels', id ?? 'noop'),
queryFn: () => adminClient.channels.get(id as string),
enabled: !!id,
})
}
export function useCreateChannel() {
- const { storeId } = useStore()
return useResourceMutation<Channel, Error, ChannelCreateParams>({
mutationFn: (params) => adminClient.channels.create(params),
- invalidate: [channelsQueryKey(storeId)],
+ invalidate: [['channels']],
successMessage: 'Channel created',
errorMessage: 'Failed to create channel',
})
}
export function useUpdateChannel(id: string) {
- const { storeId } = useStore()
return useResourceMutation<Channel, Error, ChannelUpdateParams>({
mutationFn: (params) => adminClient.channels.update(id, params),
- invalidate: [channelsQueryKey(storeId), channelQueryKey(storeId, id)],
+ invalidate: [['channels'], ['channels', id]],
successMessage: 'Channel updated',
errorMessage: 'Failed to update channel',
})
@@ -61,15 +50,15 @@ export function useUpdateChannel(id: string) {
export function useDeleteChannel() {
const queryClient = useQueryClient()
- const { storeId } = useStore()
+ const buildKey = useResourceKeyBuilder()
return useResourceMutation<void, Error, string>({
mutationFn: (id) => adminClient.channels.delete(id),
- invalidate: [channelsQueryKey(storeId)],
+ invalidate: [['channels']],
successMessage: 'Channel deleted',
errorMessage: 'Failed to delete channel',
onSuccess: (_data, id) => {
- queryClient.removeQueries({ queryKey: channelQueryKey(storeId, id) })
+ queryClient.removeQueries({ queryKey: buildKey('channels', id) })
},
})
}
diff --git a/packages/dashboard/src/hooks/use-customer-groups.ts b/packages/dashboard/src/hooks/use-customer-groups.ts
index 3be1c4d6bb..3e17dd9217 100644
--- a/packages/dashboard/src/hooks/use-customer-groups.ts
+++ b/packages/dashboard/src/hooks/use-customer-groups.ts
@@ -3,7 +3,12 @@ import type {
CustomerGroupCreateParams,
CustomerGroupUpdateParams,
} from '@spree/admin-sdk'
-import { adminClient, useResourceMutation } from '@spree/dashboard-core'
+import {
+ adminClient,
+ useResourceKey,
+ useResourceKeyBuilder,
+ useResourceMutation,
+} from '@spree/dashboard-core'
import { useQuery, useQueryClient } from '@tanstack/react-query'
/**
@@ -23,17 +28,10 @@ export function customerGroupAutocompleteProps(queryKey: string) {
}
}
-export const customerGroupsQueryKey = ['customer-groups'] as const
-
-export function customerGroupQueryKey(id: string, expand?: string[]) {
- return expand?.length
- ? (['customer-groups', id, { expand }] as const)
- : (['customer-groups', id] as const)
-}
-
export function useCustomerGroup(id: string | undefined, expand?: string[]) {
+ const base = useResourceKey('customer-groups', id ?? 'noop')
return useQuery({
- queryKey: id ? customerGroupQueryKey(id, expand) : ['customer-groups', 'noop'],
+ queryKey: expand?.length ? [...base, { expand }] : base,
queryFn: () => adminClient.customerGroups.get(id as string, { expand }),
enabled: !!id,
})
@@ -42,7 +40,7 @@ export function useCustomerGroup(id: string | undefined, expand?: string[]) {
export function useCreateCustomerGroup() {
return useResourceMutation<CustomerGroup, Error, CustomerGroupCreateParams>({
mutationFn: (params) => adminClient.customerGroups.create(params),
- invalidate: [customerGroupsQueryKey],
+ invalidate: [['customer-groups']],
successMessage: 'Customer group created',
errorMessage: 'Failed to create customer group',
})
@@ -51,7 +49,7 @@ export function useCreateCustomerGroup() {
export function useUpdateCustomerGroup(id: string) {
return useResourceMutation<CustomerGroup, Error, CustomerGroupUpdateParams>({
mutationFn: (params) => adminClient.customerGroups.update(id, params),
- invalidate: [customerGroupsQueryKey, customerGroupQueryKey(id)],
+ invalidate: [['customer-groups'], ['customer-groups', id]],
successMessage: 'Customer group updated',
errorMessage: 'Failed to update customer group',
})
@@ -59,14 +57,15 @@ export function useUpdateCustomerGroup(id: string) {
export function useDeleteCustomerGroup() {
const queryClient = useQueryClient()
+ const buildKey = useResourceKeyBuilder()
return useResourceMutation<void, Error, string>({
mutationFn: (id) => adminClient.customerGroups.delete(id),
- invalidate: [customerGroupsQueryKey],
+ invalidate: [['customer-groups']],
successMessage: 'Customer group deleted',
errorMessage: 'Failed to delete customer group',
onSuccess: (_data, id) => {
- queryClient.removeQueries({ queryKey: customerGroupQueryKey(id) })
+ queryClient.removeQueries({ queryKey: buildKey('customer-groups', id) })
},
})
}
diff --git a/packages/dashboard/src/hooks/use-customer-store-credits.ts b/packages/dashboard/src/hooks/use-customer-store-credits.ts
index e39af1235e..d73b5c05ea 100644
--- a/packages/dashboard/src/hooks/use-customer-store-credits.ts
+++ b/packages/dashboard/src/hooks/use-customer-store-credits.ts
@@ -1,5 +1,4 @@
import { adminClient, i18n, useResourceMutation } from '@spree/dashboard-core'
-import { customerQueryKey } from '@/hooks/use-customers'
type StoreCreditCreateParams = Parameters<typeof adminClient.customers.storeCredits.create>[1]
type StoreCreditUpdateParams = Parameters<typeof adminClient.customers.storeCredits.update>[2]
@@ -10,7 +9,7 @@ export function useCreateCustomerStoreCredit(customerId: string) {
return useResourceMutation({
mutationFn: (params: StoreCreditCreateParams) =>
adminClient.customers.storeCredits.create(customerId, params),
- invalidate: [customerQueryKey(customerId)],
+ invalidate: [['customers', customerId]],
successMessage: i18n.t('admin.messages.store_credit_saved'),
})
}
@@ -19,7 +18,7 @@ export function useUpdateCustomerStoreCredit(customerId: string, creditId: strin
return useResourceMutation({
mutationFn: (params: StoreCreditUpdateParams) =>
adminClient.customers.storeCredits.update(customerId, creditId, params),
- invalidate: [customerQueryKey(customerId)],
+ invalidate: [['customers', customerId]],
successMessage: i18n.t('admin.messages.store_credit_saved'),
})
}
@@ -27,7 +26,7 @@ export function useUpdateCustomerStoreCredit(customerId: string, creditId: strin
export function useDeleteCustomerStoreCredit(customerId: string) {
return useResourceMutation({
mutationFn: (id: string) => adminClient.customers.storeCredits.delete(customerId, id),
- invalidate: [customerQueryKey(customerId)],
+ invalidate: [['customers', customerId]],
successMessage: i18n.t('admin.messages.store_credit_removed'),
})
}
diff --git a/packages/dashboard/src/hooks/use-customers.ts b/packages/dashboard/src/hooks/use-customers.ts
index 878a1653d2..2eb8033d2f 100644
--- a/packages/dashboard/src/hooks/use-customers.ts
+++ b/packages/dashboard/src/hooks/use-customers.ts
@@ -1,5 +1,11 @@
import type { Customer } from '@spree/admin-sdk'
-import { adminClient, i18n, useAuth, useResourceMutation } from '@spree/dashboard-core'
+import {
+ adminClient,
+ i18n,
+ useAuth,
+ useResourceKey,
+ useResourceMutation,
+} from '@spree/dashboard-core'
import { useQuery } from '@tanstack/react-query'
/**
@@ -23,14 +29,10 @@ export function customerAutocompleteProps(queryKey: string) {
}
}
-export function customerQueryKey(customerId: string) {
- return ['customer', customerId] as const
-}
-
export function useCustomer(customerId: string) {
const { isAuthenticated } = useAuth()
return useQuery({
- queryKey: customerQueryKey(customerId),
+ queryKey: useResourceKey('customers', customerId),
queryFn: () =>
adminClient.customers.get(customerId, { expand: ['addresses', 'store_credits'] }),
enabled: isAuthenticated,
@@ -42,7 +44,7 @@ type CustomerUpdateParams = Parameters<typeof adminClient.customers.update>[1]
export function useUpdateCustomer(customerId: string) {
return useResourceMutation({
mutationFn: (params: CustomerUpdateParams) => adminClient.customers.update(customerId, params),
- invalidate: [customerQueryKey(customerId)],
+ invalidate: [['customers', customerId]],
successMessage: i18n.t('admin.messages.customer_saved'),
})
}
@@ -50,7 +52,7 @@ export function useUpdateCustomer(customerId: string) {
export function useDeleteCustomer(customerId: string) {
return useResourceMutation({
mutationFn: () => adminClient.customers.delete(customerId),
- invalidate: [['customers'], customerQueryKey(customerId)],
+ invalidate: [['customers'], ['customers', customerId]],
successMessage: i18n.t('admin.messages.customer_deleted'),
})
}
@@ -60,7 +62,13 @@ export function useDeleteCustomer(customerId: string) {
export function useCustomerOrders(customerId: string, params: { limit: number; status?: string }) {
const { isAuthenticated } = useAuth()
return useQuery({
- queryKey: ['customer-orders', customerId, params.limit, params.status ?? null] as const,
+ queryKey: useResourceKey(
+ 'customers',
+ customerId,
+ 'orders',
+ params.limit,
+ params.status ?? null,
+ ),
queryFn: () =>
adminClient.orders.list({
user_id_eq: customerId,
@@ -84,7 +92,7 @@ export function useCreateCustomerAddress(customerId: string) {
return useResourceMutation({
mutationFn: (params: AddressCreateParams) =>
adminClient.customers.addresses.create(customerId, params),
- invalidate: [customerQueryKey(customerId)],
+ invalidate: [['customers', customerId]],
successMessage: i18n.t('admin.messages.address_saved'),
})
}
@@ -93,7 +101,7 @@ export function useUpdateCustomerAddress(customerId: string) {
return useResourceMutation({
mutationFn: ({ id, params }: { id: string; params: AddressUpdateParams }) =>
adminClient.customers.addresses.update(customerId, id, params),
- invalidate: [customerQueryKey(customerId)],
+ invalidate: [['customers', customerId]],
successMessage: i18n.t('admin.messages.address_saved'),
})
}
@@ -101,7 +109,7 @@ export function useUpdateCustomerAddress(customerId: string) {
export function useDeleteCustomerAddress(customerId: string) {
return useResourceMutation({
mutationFn: (id: string) => adminClient.customers.addresses.delete(customerId, id),
- invalidate: [customerQueryKey(customerId)],
+ invalidate: [['customers', customerId]],
successMessage: i18n.t('admin.messages.address_removed'),
})
}
diff --git a/packages/dashboard/src/hooks/use-gift-cards.ts b/packages/dashboard/src/hooks/use-gift-cards.ts
index 69dc68e239..3963e566ab 100644
--- a/packages/dashboard/src/hooks/use-gift-cards.ts
+++ b/packages/dashboard/src/hooks/use-gift-cards.ts
@@ -5,18 +5,19 @@ import type {
GiftCardCreateParams,
GiftCardUpdateParams,
} from '@spree/admin-sdk'
-import { adminClient, i18n, useResourceMutation } from '@spree/dashboard-core'
+import {
+ adminClient,
+ i18n,
+ useResourceKey,
+ useResourceKeyBuilder,
+ useResourceMutation,
+} from '@spree/dashboard-core'
import { useQuery, useQueryClient } from '@tanstack/react-query'
-export const giftCardsQueryKey = ['gift-cards'] as const
-
-export function giftCardQueryKey(id: string, expand?: string[]) {
- return expand?.length ? (['gift-cards', id, { expand }] as const) : (['gift-cards', id] as const)
-}
-
export function useGiftCard(id: string | undefined, expand?: string[]) {
+ const base = useResourceKey('gift-cards', id ?? 'noop')
return useQuery({
- queryKey: id ? giftCardQueryKey(id, expand) : ['gift-cards', 'noop'],
+ queryKey: expand?.length ? [...base, { expand }] : base,
queryFn: () => adminClient.giftCards.get(id as string, { expand }),
enabled: !!id,
})
@@ -29,7 +30,7 @@ export function listGiftCards(params: Parameters<typeof adminClient.giftCards.li
export function useCreateGiftCard() {
return useResourceMutation<GiftCard, Error, GiftCardCreateParams>({
mutationFn: (params) => adminClient.giftCards.create(params),
- invalidate: [giftCardsQueryKey],
+ invalidate: [['gift-cards']],
successMessage: i18n.t('admin.gift_cards.messages.created'),
errorMessage: i18n.t('admin.gift_cards.messages.create_failed'),
})
@@ -38,7 +39,7 @@ export function useCreateGiftCard() {
export function useUpdateGiftCard(id: string) {
return useResourceMutation<GiftCard, Error, GiftCardUpdateParams>({
mutationFn: (params) => adminClient.giftCards.update(id, params),
- invalidate: [giftCardsQueryKey, giftCardQueryKey(id)],
+ invalidate: [['gift-cards'], ['gift-cards', id]],
successMessage: i18n.t('admin.gift_cards.messages.updated'),
errorMessage: i18n.t('admin.gift_cards.messages.update_failed'),
})
@@ -46,14 +47,15 @@ export function useUpdateGiftCard(id: string) {
export function useDeleteGiftCard() {
const queryClient = useQueryClient()
+ const buildKey = useResourceKeyBuilder()
return useResourceMutation<void, Error, string>({
mutationFn: (id) => adminClient.giftCards.delete(id),
- invalidate: [giftCardsQueryKey],
+ invalidate: [['gift-cards']],
successMessage: i18n.t('admin.gift_cards.messages.deleted'),
errorMessage: i18n.t('admin.gift_cards.messages.delete_failed'),
onSuccess: (_data, id) => {
- queryClient.removeQueries({ queryKey: giftCardQueryKey(id) })
+ queryClient.removeQueries({ queryKey: buildKey('gift-cards', id) })
},
})
}
@@ -62,15 +64,13 @@ export function useDeleteGiftCard() {
// Batches
// ---------------------------------------------------------------------------
-export const giftCardBatchesQueryKey = ['gift-card-batches'] as const
-
export function useCreateGiftCardBatch() {
return useResourceMutation<GiftCardBatch, Error, GiftCardBatchCreateParams>({
mutationFn: (params) => adminClient.giftCardBatches.create(params),
// Creating a batch generates N cards inline (or kicks off a job for
// larger batches), so the gift cards list is the surface that needs to
// refetch — not the batches collection itself.
- invalidate: [giftCardsQueryKey, giftCardBatchesQueryKey],
+ invalidate: [['gift-cards'], ['gift-card-batches']],
successMessage: i18n.t('admin.gift_cards.messages.batch_created'),
errorMessage: i18n.t('admin.gift_cards.messages.batch_create_failed'),
})
diff --git a/packages/dashboard/src/hooks/use-markets.ts b/packages/dashboard/src/hooks/use-markets.ts
index 3f8de0a302..4c708adca0 100644
--- a/packages/dashboard/src/hooks/use-markets.ts
+++ b/packages/dashboard/src/hooks/use-markets.ts
@@ -1,13 +1,12 @@
import type { Market, MarketCreateParams, MarketUpdateParams } from '@spree/admin-sdk'
-import { adminClient, useResourceMutation, useStore } from '@spree/dashboard-core'
+import {
+ adminClient,
+ useResourceKey,
+ useResourceKeyBuilder,
+ useResourceMutation,
+} from '@spree/dashboard-core'
import { useQuery, useQueryClient } from '@tanstack/react-query'
-export const marketsQueryKey = ['markets'] as const
-
-export function marketQueryKey(id: string) {
- return ['markets', id] as const
-}
-
interface UseMarketsParams {
page?: number
limit?: number
@@ -16,7 +15,7 @@ interface UseMarketsParams {
export function useMarkets({ page = 1, limit = 100, expand }: UseMarketsParams = {}) {
return useQuery({
- queryKey: [...marketsQueryKey, { page, limit, expand: expand?.join(',') ?? '' }],
+ queryKey: useResourceKey('markets', { page, limit, expand: expand?.join(',') ?? '' }),
queryFn: () => adminClient.markets.list({ page, limit, ...(expand ? { expand } : {}) }),
staleTime: 1000 * 60 * 5,
})
@@ -26,13 +25,11 @@ export function useMarkets({ page = 1, limit = 100, expand }: UseMarketsParams =
* Cached full-list fetch for markets — markets are store-scoped, rarely
* change, and a store typically has only a handful. Reused by pickers
* (e.g. the Market price rule) that need to filter client-side without
- * round-tripping the API on each keystroke. `storeId` is in the key so
- * switching stores doesn't surface another store's markets.
+ * round-tripping the API on each keystroke.
*/
export function useAllMarkets() {
- const { storeId } = useStore()
const { data, isLoading } = useQuery({
- queryKey: [...marketsQueryKey, storeId, 'all'],
+ queryKey: useResourceKey('markets', 'all'),
queryFn: () => adminClient.markets.list({ limit: 100, sort: 'position' }),
staleTime: 1000 * 60 * 30,
})
@@ -42,7 +39,7 @@ export function useAllMarkets() {
export function useMarket(id: string | undefined) {
return useQuery({
- queryKey: id ? marketQueryKey(id) : ['markets', 'noop'],
+ queryKey: useResourceKey('markets', id ?? 'noop'),
queryFn: () => adminClient.markets.get(id as string),
enabled: !!id,
})
@@ -51,7 +48,7 @@ export function useMarket(id: string | undefined) {
export function useCreateMarket() {
return useResourceMutation<Market, Error, MarketCreateParams>({
mutationFn: (params) => adminClient.markets.create(params),
- invalidate: [marketsQueryKey],
+ invalidate: [['markets']],
successMessage: 'Market created',
errorMessage: 'Failed to create market',
})
@@ -60,7 +57,7 @@ export function useCreateMarket() {
export function useUpdateMarket(id: string) {
return useResourceMutation<Market, Error, MarketUpdateParams>({
mutationFn: (params) => adminClient.markets.update(id, params),
- invalidate: [marketsQueryKey, marketQueryKey(id)],
+ invalidate: [['markets'], ['markets', id]],
successMessage: 'Market updated',
errorMessage: 'Failed to update market',
})
@@ -68,14 +65,15 @@ export function useUpdateMarket(id: string) {
export function useDeleteMarket() {
const queryClient = useQueryClient()
+ const buildKey = useResourceKeyBuilder()
return useResourceMutation<void, Error, string>({
mutationFn: (id) => adminClient.markets.delete(id),
- invalidate: [marketsQueryKey],
+ invalidate: [['markets']],
successMessage: 'Market deleted',
errorMessage: 'Failed to delete market',
onSuccess: (_data, id) => {
- queryClient.removeQueries({ queryKey: marketQueryKey(id) })
+ queryClient.removeQueries({ queryKey: buildKey('markets', id) })
},
})
}
diff --git a/packages/dashboard/src/hooks/use-option-types.ts b/packages/dashboard/src/hooks/use-option-types.ts
index f702abfbac..53ff4dacd1 100644
--- a/packages/dashboard/src/hooks/use-option-types.ts
+++ b/packages/dashboard/src/hooks/use-option-types.ts
@@ -1,13 +1,12 @@
import type { OptionType, OptionTypeCreateParams, OptionTypeUpdateParams } from '@spree/admin-sdk'
-import { adminClient, useResourceMutation } from '@spree/dashboard-core'
+import {
+ adminClient,
+ useResourceKey,
+ useResourceKeyBuilder,
+ useResourceMutation,
+} from '@spree/dashboard-core'
import { useQuery, useQueryClient } from '@tanstack/react-query'
-export const optionTypesQueryKey = ['option-types'] as const
-
-export function optionTypeQueryKey(id: string) {
- return ['option-types', id] as const
-}
-
interface UseOptionTypesParams {
page?: number
limit?: number
@@ -16,7 +15,7 @@ interface UseOptionTypesParams {
export function useOptionTypes({ page = 1, limit = 100, q }: UseOptionTypesParams = {}) {
return useQuery({
- queryKey: [...optionTypesQueryKey, { page, limit, q }],
+ queryKey: useResourceKey('option-types', { page, limit, q }),
queryFn: () =>
adminClient.optionTypes.list({
page,
@@ -30,7 +29,7 @@ export function useOptionTypes({ page = 1, limit = 100, q }: UseOptionTypesParam
export function useOptionType(id: string | undefined) {
return useQuery({
- queryKey: id ? optionTypeQueryKey(id) : ['option-types', 'noop'],
+ queryKey: useResourceKey('option-types', id ?? 'noop'),
queryFn: () => adminClient.optionTypes.get(id as string, { expand: ['option_values'] }),
enabled: !!id,
})
@@ -39,7 +38,7 @@ export function useOptionType(id: string | undefined) {
export function useCreateOptionType() {
return useResourceMutation<OptionType, Error, OptionTypeCreateParams>({
mutationFn: (params) => adminClient.optionTypes.create(params),
- invalidate: [optionTypesQueryKey],
+ invalidate: [['option-types']],
successMessage: 'Option type created',
errorMessage: 'Failed to create option type',
})
@@ -48,7 +47,7 @@ export function useCreateOptionType() {
export function useUpdateOptionType(id: string) {
return useResourceMutation<OptionType, Error, OptionTypeUpdateParams>({
mutationFn: (params) => adminClient.optionTypes.update(id, params),
- invalidate: [optionTypesQueryKey, optionTypeQueryKey(id)],
+ invalidate: [['option-types'], ['option-types', id]],
successMessage: 'Option type updated',
errorMessage: 'Failed to update option type',
})
@@ -56,14 +55,15 @@ export function useUpdateOptionType(id: string) {
export function useDeleteOptionType() {
const queryClient = useQueryClient()
+ const buildKey = useResourceKeyBuilder()
return useResourceMutation<void, Error, string>({
mutationFn: (id) => adminClient.optionTypes.delete(id),
- invalidate: [optionTypesQueryKey],
+ invalidate: [['option-types']],
successMessage: 'Option type deleted',
errorMessage: 'Failed to delete option type',
onSuccess: (_data, id) => {
- queryClient.removeQueries({ queryKey: optionTypeQueryKey(id) })
+ queryClient.removeQueries({ queryKey: buildKey('option-types', id) })
},
})
}
diff --git a/packages/dashboard/src/hooks/use-order.ts b/packages/dashboard/src/hooks/use-order.ts
index a75ce5706e..66ae4ad5e0 100644
--- a/packages/dashboard/src/hooks/use-order.ts
+++ b/packages/dashboard/src/hooks/use-order.ts
@@ -1,12 +1,9 @@
-import { adminClient } from '@spree/dashboard-core'
-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
-
-export const orderQueryKey = (id: string) => ['order', id] as const
-export const ordersQueryKey = ['orders'] as const
+import { adminClient, useResourceKey, useResourceKeyBuilder } from '@spree/dashboard-core'
+import { type QueryKey, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
export function useOrder(orderId: string) {
return useQuery({
- queryKey: orderQueryKey(orderId),
+ queryKey: useResourceKey('orders', orderId),
queryFn: () =>
adminClient.orders.get(orderId, {
expand: [
@@ -40,8 +37,17 @@ export function useOrderMutation<TParams>(
mutationFn: (params: TParams) => Promise<unknown>,
) {
const queryClient = useQueryClient()
+ const buildKey = useResourceKeyBuilder()
return useMutation({
mutationFn,
- onSuccess: () => queryClient.invalidateQueries({ queryKey: orderQueryKey(orderId) }),
+ onSuccess: () => queryClient.invalidateQueries({ queryKey: buildKey('orders', orderId) }),
})
}
+
+/**
+ * Bare logical key for an order — pass to `useResourceMutation`'s
+ * `invalidate:` and the storeId will be auto-injected at position 1.
+ */
+export function orderQueryKey(orderId: string): QueryKey {
+ return ['orders', orderId]
+}
diff --git a/packages/dashboard/src/hooks/use-payment-methods.ts b/packages/dashboard/src/hooks/use-payment-methods.ts
index ab3b82b390..2239c9ae38 100644
--- a/packages/dashboard/src/hooks/use-payment-methods.ts
+++ b/packages/dashboard/src/hooks/use-payment-methods.ts
@@ -3,25 +3,25 @@ import type {
PaymentMethodCreateParams,
PaymentMethodUpdateParams,
} from '@spree/admin-sdk'
-import { adminClient, useResourceMutation } from '@spree/dashboard-core'
+import {
+ adminClient,
+ useResourceKey,
+ useResourceKeyBuilder,
+ useResourceMutation,
+} from '@spree/dashboard-core'
import { useQuery, useQueryClient } from '@tanstack/react-query'
-export const paymentMethodTypesQueryKey = ['payment-methods', 'types'] as const
-
export function usePaymentMethodTypes() {
+ // Store-scoped because the server filters out providers already installed
+ // on the current store. Matches the +['payment-methods', 'types']+ shape
+ // that +useResourceMutation+ expands to +['payment-methods', storeId, 'types']+.
return useQuery({
- queryKey: paymentMethodTypesQueryKey,
+ queryKey: useResourceKey('payment-methods', 'types'),
queryFn: () => adminClient.paymentMethods.types(),
staleTime: Infinity,
})
}
-export const paymentMethodsQueryKey = ['payment-methods'] as const
-
-export function paymentMethodQueryKey(id: string) {
- return ['payment-methods', id] as const
-}
-
interface UsePaymentMethodsParams {
page?: number
limit?: number
@@ -29,14 +29,14 @@ interface UsePaymentMethodsParams {
export function usePaymentMethods({ page = 1, limit = 100 }: UsePaymentMethodsParams = {}) {
return useQuery({
- queryKey: [...paymentMethodsQueryKey, { page, limit }],
+ queryKey: useResourceKey('payment-methods', { page, limit }),
queryFn: () => adminClient.paymentMethods.list({ page, limit }),
})
}
export function usePaymentMethod(id: string | undefined) {
return useQuery({
- queryKey: id ? paymentMethodQueryKey(id) : ['payment-methods', 'noop'],
+ queryKey: useResourceKey('payment-methods', id ?? 'noop'),
queryFn: () => adminClient.paymentMethods.get(id as string),
enabled: !!id,
})
@@ -47,7 +47,7 @@ export function useCreatePaymentMethod() {
// providers, so the picker should drop the just-added one.
return useResourceMutation<PaymentMethod, Error, PaymentMethodCreateParams>({
mutationFn: (params) => adminClient.paymentMethods.create(params),
- invalidate: [paymentMethodsQueryKey, paymentMethodTypesQueryKey],
+ invalidate: [['payment-methods'], ['payment-methods', 'types']],
successMessage: 'Payment method created',
errorMessage: 'Failed to create payment method',
})
@@ -56,7 +56,7 @@ export function useCreatePaymentMethod() {
export function useUpdatePaymentMethod(id: string) {
return useResourceMutation<PaymentMethod, Error, PaymentMethodUpdateParams>({
mutationFn: (params) => adminClient.paymentMethods.update(id, params),
- invalidate: [paymentMethodsQueryKey, paymentMethodQueryKey(id)],
+ invalidate: [['payment-methods'], ['payment-methods', id]],
successMessage: 'Payment method updated',
errorMessage: 'Failed to update payment method',
})
@@ -64,14 +64,15 @@ export function useUpdatePaymentMethod(id: string) {
export function useDeletePaymentMethod() {
const queryClient = useQueryClient()
+ const buildKey = useResourceKeyBuilder()
return useResourceMutation<void, Error, string>({
mutationFn: (id) => adminClient.paymentMethods.delete(id),
- invalidate: [paymentMethodsQueryKey, paymentMethodTypesQueryKey],
+ invalidate: [['payment-methods'], ['payment-methods', 'types']],
successMessage: 'Payment method deleted',
errorMessage: 'Failed to delete payment method',
onSuccess: (_data, id) => {
- queryClient.removeQueries({ queryKey: paymentMethodQueryKey(id) })
+ queryClient.removeQueries({ queryKey: buildKey('payment-methods', id) })
},
})
}
diff --git a/packages/dashboard/src/hooks/use-price-lists.ts b/packages/dashboard/src/hooks/use-price-lists.ts
index f442c43c2f..1bb8db5c2c 100644
--- a/packages/dashboard/src/hooks/use-price-lists.ts
+++ b/packages/dashboard/src/hooks/use-price-lists.ts
@@ -1,18 +1,16 @@
import type { PriceList, PriceListCreateParams, PriceListUpdateParams } from '@spree/admin-sdk'
-import { adminClient, useResourceMutation } from '@spree/dashboard-core'
+import {
+ adminClient,
+ useResourceKey,
+ useResourceKeyBuilder,
+ useResourceMutation,
+} from '@spree/dashboard-core'
import { useQuery, useQueryClient } from '@tanstack/react-query'
-export const priceListsQueryKey = ['price-lists'] as const
-
-export function priceListQueryKey(id: string, expand?: string[]) {
- return expand?.length
- ? (['price-lists', id, { expand }] as const)
- : (['price-lists', id] as const)
-}
-
export function usePriceList(id: string | undefined, expand?: string[]) {
+ const base = useResourceKey('price-lists', id ?? 'noop')
return useQuery({
- queryKey: id ? priceListQueryKey(id, expand) : ['price-lists', 'noop'],
+ queryKey: expand?.length ? [...base, { expand }] : base,
queryFn: () => adminClient.priceLists.get(id as string, { expand }),
enabled: !!id,
})
@@ -21,7 +19,7 @@ export function usePriceList(id: string | undefined, expand?: string[]) {
export function useCreatePriceList() {
return useResourceMutation<PriceList, Error, PriceListCreateParams>({
mutationFn: (params) => adminClient.priceLists.create(params),
- invalidate: [priceListsQueryKey],
+ invalidate: [['price-lists']],
successMessage: 'Price list created',
errorMessage: 'Failed to create price list',
})
@@ -30,7 +28,7 @@ export function useCreatePriceList() {
export function useUpdatePriceList(id: string) {
return useResourceMutation<PriceList, Error, PriceListUpdateParams>({
mutationFn: (params) => adminClient.priceLists.update(id, params),
- invalidate: [priceListsQueryKey, priceListQueryKey(id)],
+ invalidate: [['price-lists'], ['price-lists', id]],
successMessage: 'Price list updated',
errorMessage: 'Failed to update price list',
})
@@ -38,14 +36,15 @@ export function useUpdatePriceList(id: string) {
export function useDeletePriceList() {
const queryClient = useQueryClient()
+ const buildKey = useResourceKeyBuilder()
return useResourceMutation<void, Error, string>({
mutationFn: (id) => adminClient.priceLists.delete(id),
- invalidate: [priceListsQueryKey],
+ invalidate: [['price-lists']],
successMessage: 'Price list deleted',
errorMessage: 'Failed to delete price list',
onSuccess: (_data, id) => {
- queryClient.removeQueries({ queryKey: priceListQueryKey(id) })
+ queryClient.removeQueries({ queryKey: buildKey('price-lists', id) })
},
})
}
@@ -53,7 +52,7 @@ export function useDeletePriceList() {
export function useActivatePriceList(id: string) {
return useResourceMutation<PriceList, Error, void>({
mutationFn: () => adminClient.priceLists.activate(id),
- invalidate: [priceListsQueryKey, priceListQueryKey(id)],
+ invalidate: [['price-lists'], ['price-lists', id]],
successMessage: 'Price list activated',
errorMessage: 'Failed to activate price list',
})
@@ -62,7 +61,7 @@ export function useActivatePriceList(id: string) {
export function useDeactivatePriceList(id: string) {
return useResourceMutation<PriceList, Error, void>({
mutationFn: () => adminClient.priceLists.deactivate(id),
- invalidate: [priceListsQueryKey, priceListQueryKey(id)],
+ invalidate: [['price-lists'], ['price-lists', id]],
successMessage: 'Price list deactivated',
errorMessage: 'Failed to deactivate price list',
})
@@ -72,23 +71,13 @@ export function useDeactivatePriceList(id: string) {
// mutation hook for the spreadsheet anymore.
// ---------------------------------------------------------------------------
-// Price Rule type discovery
+// Price Rule type discovery — registry is static, no store scope needed.
// ---------------------------------------------------------------------------
-//
-// Rules themselves aren't a separate REST resource — the SPA ships them
-// inline on the price list `update` payload via `rules: [...]`. The
-// `ruleTypes` lookup below is the one piece of separately-fetched data
-// the rule editor needs: the registry of available subclasses (and their
-// `preference_schema`) so the "Add rule" picker + generic preferences
-// form know what to render.
-
-const priceRuleTypesQueryKey = ['price-rule-types'] as const
export function usePriceRuleTypes() {
return useQuery({
- queryKey: priceRuleTypesQueryKey,
+ queryKey: ['price-rule-types'],
queryFn: () => adminClient.priceLists.ruleTypes(),
- // Registry is static; cache for the session.
staleTime: Infinity,
})
}
diff --git a/packages/dashboard/src/hooks/use-prices.ts b/packages/dashboard/src/hooks/use-prices.ts
index d3183a689c..cb9805f8d9 100644
--- a/packages/dashboard/src/hooks/use-prices.ts
+++ b/packages/dashboard/src/hooks/use-prices.ts
@@ -1,6 +1,5 @@
import type { PriceBulkUpsertRow } from '@spree/admin-sdk'
-import { adminClient } from '@spree/dashboard-core'
-import { useMutation, useQueryClient } from '@tanstack/react-query'
+import { adminClient, useResourceMutation } from '@spree/dashboard-core'
/**
* Mutation hook for the bulk-upsert endpoint behind the price spreadsheet.
@@ -10,12 +9,10 @@ import { useMutation, useQueryClient } from '@tanstack/react-query'
* so the spreadsheet can render its own dirty-state UI on failure.
*/
export function useBulkUpsertPrices() {
- const queryClient = useQueryClient()
-
- return useMutation({
- mutationFn: (params: { prices: PriceBulkUpsertRow[] }) => adminClient.prices.bulkUpsert(params),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: ['prices'] })
- },
+ return useResourceMutation<{ price_count: number }, Error, { prices: PriceBulkUpsertRow[] }>({
+ mutationFn: (params) => adminClient.prices.bulkUpsert(params),
+ invalidate: [['prices']],
+ successMessage: false,
+ errorMessage: false,
})
}
diff --git a/packages/dashboard/src/hooks/use-product-media.ts b/packages/dashboard/src/hooks/use-product-media.ts
index 93a4c6c336..838562b202 100644
--- a/packages/dashboard/src/hooks/use-product-media.ts
+++ b/packages/dashboard/src/hooks/use-product-media.ts
@@ -1,12 +1,12 @@
import type { Media } from '@spree/admin-sdk'
-import { adminClient } from '@spree/dashboard-core'
+import { adminClient, useResourceKey, useResourceKeyBuilder } from '@spree/dashboard-core'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
type MediaListSnapshot = { data: Media[] }
export function useProductMedia(productId: string) {
return useQuery({
- queryKey: ['products', productId, 'media'],
+ queryKey: useResourceKey('products', productId, 'media'),
queryFn: () => adminClient.products.media.list(productId),
enabled: !!productId,
})
@@ -14,6 +14,7 @@ export function useProductMedia(productId: string) {
export function useCreateProductMedia(productId: string) {
const queryClient = useQueryClient()
+ const buildKey = useResourceKeyBuilder()
return useMutation({
mutationFn: (params: {
@@ -23,10 +24,10 @@ export function useCreateProductMedia(productId: string) {
variant_ids?: string[]
}) => adminClient.products.media.create(productId, params),
onSuccess: (_data, variables) => {
- queryClient.invalidateQueries({ queryKey: ['products', productId, 'media'] })
- queryClient.invalidateQueries({ queryKey: ['products', productId] })
+ queryClient.invalidateQueries({ queryKey: buildKey('products', productId, 'media') })
+ queryClient.invalidateQueries({ queryKey: buildKey('products', productId) })
if (variables.variant_ids !== undefined) {
- queryClient.invalidateQueries({ queryKey: ['products', productId, 'variants'] })
+ queryClient.invalidateQueries({ queryKey: buildKey('products', productId, 'variants') })
}
},
})
@@ -34,7 +35,8 @@ export function useCreateProductMedia(productId: string) {
export function useUpdateProductMedia(productId: string) {
const queryClient = useQueryClient()
- const queryKey = ['products', productId, 'media']
+ const buildKey = useResourceKeyBuilder()
+ const queryKey = buildKey('products', productId, 'media')
return useMutation({
mutationFn: ({
@@ -81,7 +83,7 @@ export function useUpdateProductMedia(productId: string) {
onSettled: (_data, _err, variables) => {
queryClient.invalidateQueries({ queryKey })
if (variables.variant_ids !== undefined) {
- queryClient.invalidateQueries({ queryKey: ['products', productId, 'variants'] })
+ queryClient.invalidateQueries({ queryKey: buildKey('products', productId, 'variants') })
}
},
})
@@ -89,12 +91,13 @@ export function useUpdateProductMedia(productId: string) {
export function useDeleteProductMedia(productId: string) {
const queryClient = useQueryClient()
+ const buildKey = useResourceKeyBuilder()
return useMutation({
mutationFn: (id: string) => adminClient.products.media.delete(productId, id),
onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: ['products', productId, 'media'] })
- queryClient.invalidateQueries({ queryKey: ['products', productId] })
+ queryClient.invalidateQueries({ queryKey: buildKey('products', productId, 'media') })
+ queryClient.invalidateQueries({ queryKey: buildKey('products', productId) })
},
})
}
diff --git a/packages/dashboard/src/hooks/use-product.ts b/packages/dashboard/src/hooks/use-product.ts
index b5b843ff99..ad996fd854 100644
--- a/packages/dashboard/src/hooks/use-product.ts
+++ b/packages/dashboard/src/hooks/use-product.ts
@@ -1,10 +1,15 @@
-import type { ProductCreateParams, ProductUpdateParams } from '@spree/admin-sdk'
-import { adminClient } from '@spree/dashboard-core'
-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import type { Product, ProductCreateParams, ProductUpdateParams } from '@spree/admin-sdk'
+import {
+ adminClient,
+ useResourceKey,
+ useResourceKeyBuilder,
+ useResourceMutation,
+} from '@spree/dashboard-core'
+import { useQuery, useQueryClient } from '@tanstack/react-query'
export function useProduct(id: string) {
return useQuery({
- queryKey: ['products', id],
+ queryKey: useResourceKey('products', id),
queryFn: () =>
adminClient.products.get(id, {
expand: [
@@ -28,36 +33,40 @@ export function useProduct(id: string) {
}
export function useCreateProduct() {
- const queryClient = useQueryClient()
-
- return useMutation({
- mutationFn: (params: ProductCreateParams) => adminClient.products.create(params),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: ['products'] })
- },
+ return useResourceMutation<Product, Error, ProductCreateParams>({
+ mutationFn: (params) => adminClient.products.create(params),
+ invalidate: [['products']],
+ successMessage: false,
+ errorMessage: false,
})
}
export function useUpdateProduct() {
const queryClient = useQueryClient()
+ const buildKey = useResourceKeyBuilder()
- return useMutation({
- mutationFn: ({ id, ...params }: { id: string } & ProductUpdateParams) =>
- adminClient.products.update(id, params),
+ return useResourceMutation<Product, Error, { id: string } & ProductUpdateParams>({
+ mutationFn: ({ id, ...params }) => adminClient.products.update(id, params),
+ invalidate: [['products']],
+ successMessage: false,
+ errorMessage: false,
onSuccess: (_data, variables) => {
- queryClient.invalidateQueries({ queryKey: ['products', variables.id] })
- queryClient.invalidateQueries({ queryKey: ['products'] })
+ queryClient.invalidateQueries({ queryKey: buildKey('products', variables.id) })
},
})
}
export function useDeleteProduct() {
const queryClient = useQueryClient()
+ const buildKey = useResourceKeyBuilder()
- return useMutation({
- mutationFn: (id: string) => adminClient.products.delete(id),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: ['products'] })
+ return useResourceMutation<void, Error, string>({
+ mutationFn: (id) => adminClient.products.delete(id),
+ invalidate: [['products']],
+ successMessage: false,
+ errorMessage: false,
+ onSuccess: (_data, id) => {
+ queryClient.removeQueries({ queryKey: buildKey('products', id) })
},
})
}
diff --git a/packages/dashboard/src/hooks/use-products.ts b/packages/dashboard/src/hooks/use-products.ts
index f48912e56d..d4dcd93427 100644
--- a/packages/dashboard/src/hooks/use-products.ts
+++ b/packages/dashboard/src/hooks/use-products.ts
@@ -1,5 +1,5 @@
import type { FilterRule } from '@spree/dashboard-core'
-import { adminClient, useResourceMutation } from '@spree/dashboard-core'
+import { adminClient, useResourceKey, useResourceMutation } from '@spree/dashboard-core'
import { useQuery } from '@tanstack/react-query'
import i18n from 'i18next'
@@ -19,7 +19,7 @@ export function useProducts({
filters = [],
}: UseProductsParams = {}) {
return useQuery({
- queryKey: ['products', { page, limit, sort, search, filters }],
+ queryKey: useResourceKey('products', { page, limit, sort, search, filters }),
queryFn: async () => {
const params: Record<string, unknown> = { page, limit, sort }
diff --git a/packages/dashboard/src/hooks/use-promotions.ts b/packages/dashboard/src/hooks/use-promotions.ts
index 763fc7d4c0..9c6b03f359 100644
--- a/packages/dashboard/src/hooks/use-promotions.ts
+++ b/packages/dashboard/src/hooks/use-promotions.ts
@@ -9,27 +9,14 @@ import type {
PromotionRuleUpdateParams,
PromotionUpdateParams,
} from '@spree/admin-sdk'
-import { adminClient, useResourceMutation } from '@spree/dashboard-core'
+import {
+ adminClient,
+ useResourceKey,
+ useResourceKeyBuilder,
+ useResourceMutation,
+} from '@spree/dashboard-core'
import { useQuery, useQueryClient } from '@tanstack/react-query'
-export const promotionsQueryKey = ['promotions'] as const
-
-export function promotionQueryKey(id: string) {
- return ['promotions', id] as const
-}
-
-export function promotionActionsQueryKey(promotionId: string) {
- return ['promotions', promotionId, 'actions'] as const
-}
-
-export function promotionRulesQueryKey(promotionId: string) {
- return ['promotions', promotionId, 'rules'] as const
-}
-
-export function promotionCouponCodesQueryKey(promotionId: string) {
- return ['promotions', promotionId, 'coupon-codes'] as const
-}
-
interface UsePromotionsParams {
page?: number
limit?: number
@@ -37,7 +24,7 @@ interface UsePromotionsParams {
export function usePromotion(id: string | undefined) {
return useQuery({
- queryKey: id ? promotionQueryKey(id) : ['promotions', 'noop'],
+ queryKey: useResourceKey('promotions', id ?? 'noop'),
queryFn: () => adminClient.promotions.get(id as string),
enabled: !!id,
})
@@ -46,7 +33,7 @@ export function usePromotion(id: string | undefined) {
export function useCreatePromotion() {
return useResourceMutation<Promotion, Error, PromotionCreateParams>({
mutationFn: (params) => adminClient.promotions.create(params),
- invalidate: [promotionsQueryKey],
+ invalidate: [['promotions']],
successMessage: 'Promotion created',
errorMessage: 'Failed to create promotion',
})
@@ -55,7 +42,7 @@ export function useCreatePromotion() {
export function useUpdatePromotion(id: string) {
return useResourceMutation<Promotion, Error, PromotionUpdateParams>({
mutationFn: (params) => adminClient.promotions.update(id, params),
- invalidate: [promotionsQueryKey, promotionQueryKey(id)],
+ invalidate: [['promotions'], ['promotions', id]],
successMessage: 'Promotion updated',
errorMessage: 'Failed to update promotion',
})
@@ -63,14 +50,15 @@ export function useUpdatePromotion(id: string) {
export function useDeletePromotion() {
const queryClient = useQueryClient()
+ const buildKey = useResourceKeyBuilder()
return useResourceMutation<void, Error, string>({
mutationFn: (id) => adminClient.promotions.delete(id),
- invalidate: [promotionsQueryKey],
+ invalidate: [['promotions']],
successMessage: 'Promotion deleted',
errorMessage: 'Failed to delete promotion',
onSuccess: (_data, id) => {
- queryClient.removeQueries({ queryKey: promotionQueryKey(id) })
+ queryClient.removeQueries({ queryKey: buildKey('promotions', id) })
},
})
}
@@ -81,9 +69,7 @@ export function useDeletePromotion() {
export function usePromotionActions(promotionId: string | undefined) {
return useQuery({
- queryKey: promotionId
- ? promotionActionsQueryKey(promotionId)
- : ['promotions', 'noop', 'actions'],
+ queryKey: useResourceKey('promotions', promotionId ?? 'noop', 'actions'),
queryFn: () => adminClient.promotions.actions.list(promotionId as string, { limit: 100 }),
enabled: !!promotionId,
})
@@ -92,7 +78,10 @@ export function usePromotionActions(promotionId: string | undefined) {
export function useCreatePromotionAction(promotionId: string) {
return useResourceMutation<PromotionAction, Error, PromotionActionCreateParams>({
mutationFn: (params) => adminClient.promotions.actions.create(promotionId, params),
- invalidate: [promotionActionsQueryKey(promotionId), promotionQueryKey(promotionId)],
+ invalidate: [
+ ['promotions', promotionId, 'actions'],
+ ['promotions', promotionId],
+ ],
successMessage: 'Action added',
errorMessage: 'Failed to add action',
})
@@ -101,7 +90,10 @@ export function useCreatePromotionAction(promotionId: string) {
export function useUpdatePromotionAction(promotionId: string, actionId: string) {
return useResourceMutation<PromotionAction, Error, PromotionActionUpdateParams>({
mutationFn: (params) => adminClient.promotions.actions.update(promotionId, actionId, params),
- invalidate: [promotionActionsQueryKey(promotionId), promotionQueryKey(promotionId)],
+ invalidate: [
+ ['promotions', promotionId, 'actions'],
+ ['promotions', promotionId],
+ ],
successMessage: 'Action updated',
errorMessage: 'Failed to update action',
})
@@ -110,7 +102,10 @@ export function useUpdatePromotionAction(promotionId: string, actionId: string)
export function useDeletePromotionAction(promotionId: string) {
return useResourceMutation<void, Error, string>({
mutationFn: (actionId) => adminClient.promotions.actions.delete(promotionId, actionId),
- invalidate: [promotionActionsQueryKey(promotionId), promotionQueryKey(promotionId)],
+ invalidate: [
+ ['promotions', promotionId, 'actions'],
+ ['promotions', promotionId],
+ ],
successMessage: 'Action removed',
errorMessage: 'Failed to remove action',
})
@@ -122,7 +117,7 @@ export function useDeletePromotionAction(promotionId: string) {
export function usePromotionRules(promotionId: string | undefined) {
return useQuery({
- queryKey: promotionId ? promotionRulesQueryKey(promotionId) : ['promotions', 'noop', 'rules'],
+ queryKey: useResourceKey('promotions', promotionId ?? 'noop', 'rules'),
queryFn: () => adminClient.promotions.rules.list(promotionId as string, { limit: 100 }),
enabled: !!promotionId,
})
@@ -131,7 +126,10 @@ export function usePromotionRules(promotionId: string | undefined) {
export function useCreatePromotionRule(promotionId: string) {
return useResourceMutation<PromotionRule, Error, PromotionRuleCreateParams>({
mutationFn: (params) => adminClient.promotions.rules.create(promotionId, params),
- invalidate: [promotionRulesQueryKey(promotionId), promotionQueryKey(promotionId)],
+ invalidate: [
+ ['promotions', promotionId, 'rules'],
+ ['promotions', promotionId],
+ ],
successMessage: 'Rule added',
errorMessage: 'Failed to add rule',
})
@@ -140,7 +138,10 @@ export function useCreatePromotionRule(promotionId: string) {
export function useUpdatePromotionRule(promotionId: string, ruleId: string) {
return useResourceMutation<PromotionRule, Error, PromotionRuleUpdateParams>({
mutationFn: (params) => adminClient.promotions.rules.update(promotionId, ruleId, params),
- invalidate: [promotionRulesQueryKey(promotionId), promotionQueryKey(promotionId)],
+ invalidate: [
+ ['promotions', promotionId, 'rules'],
+ ['promotions', promotionId],
+ ],
successMessage: 'Rule updated',
errorMessage: 'Failed to update rule',
})
@@ -149,7 +150,10 @@ export function useUpdatePromotionRule(promotionId: string, ruleId: string) {
export function useDeletePromotionRule(promotionId: string) {
return useResourceMutation<void, Error, string>({
mutationFn: (ruleId) => adminClient.promotions.rules.delete(promotionId, ruleId),
- invalidate: [promotionRulesQueryKey(promotionId), promotionQueryKey(promotionId)],
+ invalidate: [
+ ['promotions', promotionId, 'rules'],
+ ['promotions', promotionId],
+ ],
successMessage: 'Rule removed',
errorMessage: 'Failed to remove rule',
})
@@ -164,9 +168,7 @@ export function usePromotionCouponCodes(
params: UsePromotionsParams = {},
) {
return useQuery({
- queryKey: promotionId
- ? [...promotionCouponCodesQueryKey(promotionId), params]
- : ['promotions', 'noop', 'coupon-codes'],
+ queryKey: useResourceKey('promotions', promotionId ?? 'noop', 'coupon-codes', params),
queryFn: () =>
adminClient.promotions.couponCodes.list(promotionId as string, {
page: params.page ?? 1,
@@ -180,12 +182,9 @@ export function usePromotionCouponCodes(
// Type registries (cached forever — registries are static at runtime)
// ============================================
-export const promotionActionTypesQueryKey = ['promotion-actions', 'types'] as const
-export const promotionRuleTypesQueryKey = ['promotion-rules', 'types'] as const
-
export function usePromotionActionTypes() {
return useQuery({
- queryKey: promotionActionTypesQueryKey,
+ queryKey: ['promotion-actions', 'types'],
queryFn: () => adminClient.promotionActions.types(),
staleTime: Infinity,
})
@@ -193,7 +192,7 @@ export function usePromotionActionTypes() {
export function usePromotionRuleTypes() {
return useQuery({
- queryKey: promotionRuleTypesQueryKey,
+ queryKey: ['promotion-rules', 'types'],
queryFn: () => adminClient.promotionRules.types(),
staleTime: Infinity,
})
diff --git a/packages/dashboard/src/hooks/use-staff.ts b/packages/dashboard/src/hooks/use-staff.ts
index 401241341c..10794d5f69 100644
--- a/packages/dashboard/src/hooks/use-staff.ts
+++ b/packages/dashboard/src/hooks/use-staff.ts
@@ -1,43 +1,36 @@
import type { AdminUserUpdateParams, InvitationCreateParams } from '@spree/admin-sdk'
-import { adminClient } from '@spree/dashboard-core'
-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
-
-const STAFF_KEY = ['staff'] as const
-const INVITATIONS_KEY = ['invitations'] as const
-const ROLES_KEY = ['roles'] as const
+import { adminClient, useResourceKey, useResourceMutation } from '@spree/dashboard-core'
+import { useQuery } from '@tanstack/react-query'
export function useStaff() {
return useQuery({
- queryKey: STAFF_KEY,
+ queryKey: useResourceKey('staff'),
queryFn: () => adminClient.adminUsers.list({ limit: 100 }),
})
}
export function useInvitations() {
return useQuery({
- queryKey: INVITATIONS_KEY,
+ queryKey: useResourceKey('invitations'),
queryFn: () => adminClient.invitations.list({ limit: 100 }),
})
}
export function useRoles() {
+ // Roles are global across stores; no storeId scope.
return useQuery({
- queryKey: ROLES_KEY,
+ queryKey: ['roles'],
queryFn: () => adminClient.roles.list({ limit: 100 }),
- // Roles are global; cache aggressively so the role picker doesn't refetch
- // every time the staff dialog opens.
staleTime: 5 * 60 * 1000,
})
}
export function useUpdateStaff() {
- const qc = useQueryClient()
- return useMutation({
- mutationFn: ({ id, params }: { id: string; params: AdminUserUpdateParams }) =>
- adminClient.adminUsers.update(id, params),
- onSuccess: () => {
- qc.invalidateQueries({ queryKey: STAFF_KEY })
- },
+ return useResourceMutation<unknown, Error, { id: string; params: AdminUserUpdateParams }>({
+ mutationFn: ({ id, params }) => adminClient.adminUsers.update(id, params),
+ invalidate: [['staff']],
+ successMessage: false,
+ errorMessage: false,
})
}
@@ -46,41 +39,37 @@ export function useUpdateStaff() {
* preserved — the user keeps access to any other stores.
*/
export function useRemoveStaff() {
- const qc = useQueryClient()
- return useMutation({
- mutationFn: (id: string) => adminClient.adminUsers.delete(id),
- onSuccess: () => {
- qc.invalidateQueries({ queryKey: STAFF_KEY })
- },
+ return useResourceMutation<unknown, Error, string>({
+ mutationFn: (id) => adminClient.adminUsers.delete(id),
+ invalidate: [['staff']],
+ successMessage: false,
+ errorMessage: false,
})
}
export function useCreateInvitation() {
- const qc = useQueryClient()
- return useMutation({
- mutationFn: (params: InvitationCreateParams) => adminClient.invitations.create(params),
- onSuccess: () => {
- qc.invalidateQueries({ queryKey: INVITATIONS_KEY })
- },
+ return useResourceMutation<unknown, Error, InvitationCreateParams>({
+ mutationFn: (params) => adminClient.invitations.create(params),
+ invalidate: [['invitations']],
+ successMessage: false,
+ errorMessage: false,
})
}
export function useResendInvitation() {
- const qc = useQueryClient()
- return useMutation({
- mutationFn: (id: string) => adminClient.invitations.resend(id),
- onSuccess: () => {
- qc.invalidateQueries({ queryKey: INVITATIONS_KEY })
- },
+ return useResourceMutation<unknown, Error, string>({
+ mutationFn: (id) => adminClient.invitations.resend(id),
+ invalidate: [['invitations']],
+ successMessage: false,
+ errorMessage: false,
})
}
export function useDeleteInvitation() {
- const qc = useQueryClient()
- return useMutation({
- mutationFn: (id: string) => adminClient.invitations.delete(id),
- onSuccess: () => {
- qc.invalidateQueries({ queryKey: INVITATIONS_KEY })
- },
+ return useResourceMutation<unknown, Error, string>({
+ mutationFn: (id) => adminClient.invitations.delete(id),
+ invalidate: [['invitations']],
+ successMessage: false,
+ errorMessage: false,
})
}
diff --git a/packages/dashboard/src/hooks/use-stock-items.ts b/packages/dashboard/src/hooks/use-stock-items.ts
index 77f1ffc890..83d8feba16 100644
--- a/packages/dashboard/src/hooks/use-stock-items.ts
+++ b/packages/dashboard/src/hooks/use-stock-items.ts
@@ -1,13 +1,12 @@
import type { StockItem, StockItemUpdateParams } from '@spree/admin-sdk'
-import { adminClient, useResourceMutation } from '@spree/dashboard-core'
+import {
+ adminClient,
+ useResourceKey,
+ useResourceKeyBuilder,
+ useResourceMutation,
+} from '@spree/dashboard-core'
import { type QueryKey, useQuery, useQueryClient } from '@tanstack/react-query'
-export const stockItemsQueryKey = ['stock-items'] as const
-
-export function stockItemQueryKey(id: string) {
- return ['stock-items', id] as const
-}
-
interface UseStockItemsParams {
page?: number
limit?: number
@@ -17,7 +16,7 @@ interface UseStockItemsParams {
export function useStockItems(params: UseStockItemsParams = {}) {
return useQuery({
- queryKey: [...stockItemsQueryKey, params],
+ queryKey: useResourceKey('stock-items', params),
queryFn: () =>
adminClient.stockItems.list({
page: params.page ?? 1,
@@ -41,7 +40,7 @@ export function useStockItems(params: UseStockItemsParams = {}) {
export function useUpdateStockItem(id: string, extraInvalidate: QueryKey[] = []) {
return useResourceMutation<StockItem, Error, StockItemUpdateParams>({
mutationFn: (params) => adminClient.stockItems.update(id, params),
- invalidate: [stockItemsQueryKey, stockItemQueryKey(id), ...extraInvalidate],
+ invalidate: [['stock-items'], ['stock-items', id], ...extraInvalidate],
successMessage: 'Stock updated',
errorMessage: 'Failed to update stock',
})
@@ -49,14 +48,15 @@ export function useUpdateStockItem(id: string, extraInvalidate: QueryKey[] = [])
export function useDeleteStockItem() {
const queryClient = useQueryClient()
+ const buildKey = useResourceKeyBuilder()
return useResourceMutation<void, Error, string>({
mutationFn: (id) => adminClient.stockItems.delete(id),
- invalidate: [stockItemsQueryKey],
+ invalidate: [['stock-items']],
successMessage: 'Stock item deleted',
errorMessage: 'Failed to delete stock item',
onSuccess: (_data, id) => {
- queryClient.removeQueries({ queryKey: stockItemQueryKey(id) })
+ queryClient.removeQueries({ queryKey: buildKey('stock-items', id) })
},
})
}
diff --git a/packages/dashboard/src/hooks/use-stock-locations.ts b/packages/dashboard/src/hooks/use-stock-locations.ts
index 3cb815a01a..a971a94c65 100644
--- a/packages/dashboard/src/hooks/use-stock-locations.ts
+++ b/packages/dashboard/src/hooks/use-stock-locations.ts
@@ -3,15 +3,14 @@ import type {
StockLocationCreateParams,
StockLocationUpdateParams,
} from '@spree/admin-sdk'
-import { adminClient, useResourceMutation } from '@spree/dashboard-core'
+import {
+ adminClient,
+ useResourceKey,
+ useResourceKeyBuilder,
+ useResourceMutation,
+} from '@spree/dashboard-core'
import { useQuery, useQueryClient } from '@tanstack/react-query'
-export const stockLocationsQueryKey = ['stock-locations'] as const
-
-export function stockLocationQueryKey(id: string) {
- return ['stock-locations', id] as const
-}
-
interface UseStockLocationsParams {
page?: number
limit?: number
@@ -21,14 +20,14 @@ interface UseStockLocationsParams {
// than 100 locations can paginate; the typical merchant has a handful.
export function useStockLocations({ page = 1, limit = 100 }: UseStockLocationsParams = {}) {
return useQuery({
- queryKey: [...stockLocationsQueryKey, { page, limit }],
+ queryKey: useResourceKey('stock-locations', { page, limit }),
queryFn: () => adminClient.stockLocations.list({ page, limit }),
})
}
export function useStockLocation(id: string | undefined) {
return useQuery({
- queryKey: id ? stockLocationQueryKey(id) : ['stock-locations', 'noop'],
+ queryKey: useResourceKey('stock-locations', id ?? 'noop'),
queryFn: () => adminClient.stockLocations.get(id as string),
enabled: !!id,
})
@@ -37,7 +36,7 @@ export function useStockLocation(id: string | undefined) {
export function useCreateStockLocation() {
return useResourceMutation<StockLocation, Error, StockLocationCreateParams>({
mutationFn: (params) => adminClient.stockLocations.create(params),
- invalidate: [stockLocationsQueryKey],
+ invalidate: [['stock-locations']],
successMessage: 'Stock location created',
errorMessage: 'Failed to create stock location',
})
@@ -46,7 +45,7 @@ export function useCreateStockLocation() {
export function useUpdateStockLocation(id: string) {
return useResourceMutation<StockLocation, Error, StockLocationUpdateParams>({
mutationFn: (params) => adminClient.stockLocations.update(id, params),
- invalidate: [stockLocationsQueryKey, stockLocationQueryKey(id)],
+ invalidate: [['stock-locations'], ['stock-locations', id]],
successMessage: 'Stock location updated',
errorMessage: 'Failed to update stock location',
})
@@ -54,16 +53,17 @@ export function useUpdateStockLocation(id: string) {
export function useDeleteStockLocation() {
const queryClient = useQueryClient()
+ const buildKey = useResourceKeyBuilder()
return useResourceMutation<void, Error, string>({
mutationFn: (id) => adminClient.stockLocations.delete(id),
- invalidate: [stockLocationsQueryKey],
+ invalidate: [['stock-locations']],
successMessage: 'Stock location deleted',
errorMessage: 'Failed to delete stock location',
onSuccess: (_data, id) => {
// Drop the individual-resource cache so any open detail view stops
// showing stale data after the row is gone.
- queryClient.removeQueries({ queryKey: stockLocationQueryKey(id) })
+ queryClient.removeQueries({ queryKey: buildKey('stock-locations', id) })
},
})
}
diff --git a/packages/dashboard/src/hooks/use-stock-transfers.ts b/packages/dashboard/src/hooks/use-stock-transfers.ts
index a25a566cc7..c514091833 100644
--- a/packages/dashboard/src/hooks/use-stock-transfers.ts
+++ b/packages/dashboard/src/hooks/use-stock-transfers.ts
@@ -1,16 +1,15 @@
import type { StockTransfer, StockTransferCreateParams } from '@spree/admin-sdk'
-import { adminClient, useResourceMutation } from '@spree/dashboard-core'
+import {
+ adminClient,
+ useResourceKey,
+ useResourceKeyBuilder,
+ useResourceMutation,
+} from '@spree/dashboard-core'
import { useQuery, useQueryClient } from '@tanstack/react-query'
-export const stockTransfersQueryKey = ['stock-transfers'] as const
-
-export function stockTransferQueryKey(id: string) {
- return ['stock-transfers', id] as const
-}
-
export function useStockTransfer(id: string | undefined) {
return useQuery({
- queryKey: id ? stockTransferQueryKey(id) : ['stock-transfers', 'noop'],
+ queryKey: useResourceKey('stock-transfers', id ?? 'noop'),
queryFn: () =>
adminClient.stockTransfers.get(id as string, {
expand: ['source_location', 'destination_location'],
@@ -22,7 +21,7 @@ export function useStockTransfer(id: string | undefined) {
export function useCreateStockTransfer() {
return useResourceMutation<StockTransfer, Error, StockTransferCreateParams>({
mutationFn: (params) => adminClient.stockTransfers.create(params),
- invalidate: [stockTransfersQueryKey],
+ invalidate: [['stock-transfers']],
successMessage: 'Stock transfer recorded',
errorMessage: 'Failed to record stock transfer',
})
@@ -30,14 +29,15 @@ export function useCreateStockTransfer() {
export function useDeleteStockTransfer() {
const queryClient = useQueryClient()
+ const buildKey = useResourceKeyBuilder()
return useResourceMutation<void, Error, string>({
mutationFn: (id) => adminClient.stockTransfers.delete(id),
- invalidate: [stockTransfersQueryKey],
+ invalidate: [['stock-transfers']],
successMessage: 'Stock transfer deleted',
errorMessage: 'Failed to delete stock transfer',
onSuccess: (_data, id) => {
- queryClient.removeQueries({ queryKey: stockTransferQueryKey(id) })
+ queryClient.removeQueries({ queryKey: buildKey('stock-transfers', id) })
},
})
}
diff --git a/packages/dashboard/src/hooks/use-store-settings.ts b/packages/dashboard/src/hooks/use-store-settings.ts
index 791b4b1e47..f0dda15b10 100644
--- a/packages/dashboard/src/hooks/use-store-settings.ts
+++ b/packages/dashboard/src/hooks/use-store-settings.ts
@@ -1,22 +1,22 @@
import type { StoreUpdateParams } from '@spree/admin-sdk'
-import { adminClient, useStore } from '@spree/dashboard-core'
-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import { adminClient, useResourceKey, useResourceMutation, useStore } from '@spree/dashboard-core'
+import { useQuery } from '@tanstack/react-query'
export function useStoreSettings() {
return useQuery({
- queryKey: ['store-settings'],
+ queryKey: useResourceKey('store-settings'),
queryFn: () => adminClient.store.get(),
})
}
export function useUpdateStoreSettings() {
- const queryClient = useQueryClient()
const { refetch } = useStore()
-
- return useMutation({
- mutationFn: (params: StoreUpdateParams) => adminClient.store.update(params),
+ return useResourceMutation<unknown, Error, StoreUpdateParams>({
+ mutationFn: (params) => adminClient.store.update(params),
+ invalidate: [['store-settings']],
+ successMessage: false,
+ errorMessage: false,
onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: ['store-settings'] })
refetch()
},
})
diff --git a/packages/dashboard/src/hooks/use-tax-categories.ts b/packages/dashboard/src/hooks/use-tax-categories.ts
index 3f57808060..4439cc4ebb 100644
--- a/packages/dashboard/src/hooks/use-tax-categories.ts
+++ b/packages/dashboard/src/hooks/use-tax-categories.ts
@@ -3,15 +3,14 @@ import type {
TaxCategoryCreateParams,
TaxCategoryUpdateParams,
} from '@spree/admin-sdk'
-import { adminClient, useResourceMutation } from '@spree/dashboard-core'
+import {
+ adminClient,
+ useResourceKey,
+ useResourceKeyBuilder,
+ useResourceMutation,
+} from '@spree/dashboard-core'
import { useQuery, useQueryClient } from '@tanstack/react-query'
-export const taxCategoriesQueryKey = ['tax-categories'] as const
-
-export function taxCategoryQueryKey(id: string) {
- return ['tax-categories', id] as const
-}
-
interface UseTaxCategoriesParams {
page?: number
limit?: number
@@ -19,7 +18,7 @@ interface UseTaxCategoriesParams {
export function useTaxCategories({ page = 1, limit = 100 }: UseTaxCategoriesParams = {}) {
return useQuery({
- queryKey: [...taxCategoriesQueryKey, { page, limit }],
+ queryKey: useResourceKey('tax-categories', { page, limit }),
queryFn: () => adminClient.taxCategories.list({ page, limit }),
staleTime: 1000 * 60 * 5,
})
@@ -27,7 +26,7 @@ export function useTaxCategories({ page = 1, limit = 100 }: UseTaxCategoriesPara
export function useTaxCategory(id: string | undefined) {
return useQuery({
- queryKey: id ? taxCategoryQueryKey(id) : ['tax-categories', 'noop'],
+ queryKey: useResourceKey('tax-categories', id ?? 'noop'),
queryFn: () => adminClient.taxCategories.get(id as string),
enabled: !!id,
})
@@ -36,7 +35,7 @@ export function useTaxCategory(id: string | undefined) {
export function useCreateTaxCategory() {
return useResourceMutation<TaxCategory, Error, TaxCategoryCreateParams>({
mutationFn: (params) => adminClient.taxCategories.create(params),
- invalidate: [taxCategoriesQueryKey],
+ invalidate: [['tax-categories']],
successMessage: 'Tax category created',
errorMessage: 'Failed to create tax category',
})
@@ -45,7 +44,7 @@ export function useCreateTaxCategory() {
export function useUpdateTaxCategory(id: string) {
return useResourceMutation<TaxCategory, Error, TaxCategoryUpdateParams>({
mutationFn: (params) => adminClient.taxCategories.update(id, params),
- invalidate: [taxCategoriesQueryKey, taxCategoryQueryKey(id)],
+ invalidate: [['tax-categories'], ['tax-categories', id]],
successMessage: 'Tax category updated',
errorMessage: 'Failed to update tax category',
})
@@ -53,14 +52,15 @@ export function useUpdateTaxCategory(id: string) {
export function useDeleteTaxCategory() {
const queryClient = useQueryClient()
+ const buildKey = useResourceKeyBuilder()
return useResourceMutation<void, Error, string>({
mutationFn: (id) => adminClient.taxCategories.delete(id),
- invalidate: [taxCategoriesQueryKey],
+ invalidate: [['tax-categories']],
successMessage: 'Tax category deleted',
errorMessage: 'Failed to delete tax category',
onSuccess: (_data, id) => {
- queryClient.removeQueries({ queryKey: taxCategoryQueryKey(id) })
+ queryClient.removeQueries({ queryKey: buildKey('tax-categories', id) })
},
})
}
diff --git a/packages/dashboard/src/hooks/use-variant-media.ts b/packages/dashboard/src/hooks/use-variant-media.ts
index ed5f715928..3cab305530 100644
--- a/packages/dashboard/src/hooks/use-variant-media.ts
+++ b/packages/dashboard/src/hooks/use-variant-media.ts
@@ -1,11 +1,11 @@
-import { adminClient } from '@spree/dashboard-core'
+import { adminClient, useResourceKey } from '@spree/dashboard-core'
import { useQuery } from '@tanstack/react-query'
// Lists media linked to a variant. Mutations go through useUpdateProductMedia
// with `variant_ids` — there's no variant-scoped mutation endpoint.
export function useVariantMedia(productId: string, variantId: string) {
return useQuery({
- queryKey: ['products', productId, 'variants', variantId, 'media'],
+ queryKey: useResourceKey('products', productId, 'variants', variantId, 'media'),
queryFn: () => adminClient.products.variants.media.list(productId, variantId),
enabled: !!productId && !!variantId,
})
diff --git a/packages/dashboard/src/hooks/use-webhook-endpoints.ts b/packages/dashboard/src/hooks/use-webhook-endpoints.ts
index 5c99fb8ef2..9f58b90860 100644
--- a/packages/dashboard/src/hooks/use-webhook-endpoints.ts
+++ b/packages/dashboard/src/hooks/use-webhook-endpoints.ts
@@ -4,39 +4,17 @@ import type {
WebhookEndpointCreateParams,
WebhookEndpointUpdateParams,
} from '@spree/admin-sdk'
-import { adminClient, useResourceMutation, useStore } from '@spree/dashboard-core'
+import {
+ adminClient,
+ useResourceKey,
+ useResourceKeyBuilder,
+ useResourceMutation,
+} from '@spree/dashboard-core'
import { useQuery, useQueryClient } from '@tanstack/react-query'
-// `webhookEndpointsListKey` is what `<ResourceTable queryKey="webhook-endpoints">`
-// uses internally as the prefix of its compound key (`['webhook-endpoints',
-// { page, limit, sort, search, filters }]`). Invalidating the bare prefix is
-// what gets the table to refetch — anything more specific misses.
-//
-// Detail/deliveries queries below carry `storeId` so switching stores invalidates
-// cached single-endpoint data; the list query is owned by ResourceTable, which
-// remounts when the route changes, so it doesn't need explicit store-scoping.
-export const webhookEndpointsListKey = ['webhook-endpoints'] as const
-
-export function useWebhookEndpointQueryKey(id: string | undefined) {
- const { storeId } = useStore()
- return ['webhook-endpoints', storeId, id ?? 'noop'] as const
-}
-
-/**
- * The bare prefix `<ResourceTable queryKey={…}>` uses for the embedded
- * deliveries table. The table builds a compound key `[prefix, { page, … }]`,
- * so invalidating just the prefix prefix-matches every paginated/filtered
- * snapshot. Must stay in sync with the `queryKey` prop on the
- * deliveries `<ResourceTable>` in `webhooks/$webhookEndpointId.tsx`.
- */
-export function webhookDeliveriesTableKey(endpointId: string) {
- return `webhook-deliveries:${endpointId}` as const
-}
-
export function useWebhookEndpoint(id: string | undefined) {
- const key = useWebhookEndpointQueryKey(id)
return useQuery({
- queryKey: key,
+ queryKey: useResourceKey('webhook-endpoints', id ?? 'noop'),
queryFn: () => adminClient.webhookEndpoints.get(id as string),
enabled: !!id,
})
@@ -45,7 +23,7 @@ export function useWebhookEndpoint(id: string | undefined) {
export function useCreateWebhookEndpoint() {
return useResourceMutation<WebhookEndpoint, Error, WebhookEndpointCreateParams>({
mutationFn: (params) => adminClient.webhookEndpoints.create(params),
- invalidate: [webhookEndpointsListKey],
+ invalidate: [['webhook-endpoints']],
// The creator wants the dedicated "save your secret" sheet, not a toast,
// because the secret_key in the response is only revealed once.
successMessage: false,
@@ -54,11 +32,9 @@ export function useCreateWebhookEndpoint() {
}
export function useUpdateWebhookEndpoint(id: string) {
- const detailKey = useWebhookEndpointQueryKey(id)
-
return useResourceMutation<WebhookEndpoint, Error, WebhookEndpointUpdateParams>({
mutationFn: (params) => adminClient.webhookEndpoints.update(id, params),
- invalidate: [webhookEndpointsListKey, detailKey],
+ invalidate: [['webhook-endpoints'], ['webhook-endpoints', id]],
successMessage: 'Webhook endpoint updated',
errorMessage: 'Failed to update webhook endpoint',
})
@@ -66,44 +42,40 @@ export function useUpdateWebhookEndpoint(id: string) {
export function useDeleteWebhookEndpoint() {
const queryClient = useQueryClient()
- const { storeId } = useStore()
+ const buildKey = useResourceKeyBuilder()
return useResourceMutation<void, Error, string>({
mutationFn: (id) => adminClient.webhookEndpoints.delete(id),
- invalidate: [webhookEndpointsListKey],
+ invalidate: [['webhook-endpoints']],
successMessage: 'Webhook endpoint removed',
errorMessage: 'Failed to remove webhook endpoint',
onSuccess: (_data, id) => {
- queryClient.removeQueries({
- queryKey: ['webhook-endpoints', storeId, id],
- })
+ queryClient.removeQueries({ queryKey: buildKey('webhook-endpoints', id) })
},
})
}
export function useToggleWebhookEndpoint() {
const queryClient = useQueryClient()
- const { storeId } = useStore()
+ const buildKey = useResourceKeyBuilder()
return useResourceMutation<WebhookEndpoint, Error, { id: string; active: boolean }>({
mutationFn: ({ id, active }) =>
active ? adminClient.webhookEndpoints.enable(id) : adminClient.webhookEndpoints.disable(id),
- invalidate: [webhookEndpointsListKey],
+ invalidate: [['webhook-endpoints']],
successMessage: false,
errorMessage: 'Failed to update endpoint',
onSuccess: (_data, { id }) => {
- // The detail page reads `disabled_at` + `active` directly from the
+ // Detail page reads `disabled_at` + `active` directly from the
// single-endpoint cache; invalidating only the list misses it.
- queryClient.invalidateQueries({
- queryKey: ['webhook-endpoints', storeId, id],
- })
+ queryClient.invalidateQueries({ queryKey: buildKey('webhook-endpoints', id) })
},
})
}
export function useSendTestWebhook() {
const queryClient = useQueryClient()
- const { storeId } = useStore()
+ const buildKey = useResourceKeyBuilder()
return useResourceMutation<WebhookDelivery, Error, string>({
mutationFn: (id) => adminClient.webhookEndpoints.sendTest(id),
@@ -113,24 +85,20 @@ export function useSendTestWebhook() {
// Refetch the deliveries list embedded in the detail page (the new test
// row needs to appear without a manual refresh) and the endpoint's
// detail cache (total/successful/failed counts + last_delivery_at).
- queryClient.invalidateQueries({ queryKey: [webhookDeliveriesTableKey(endpointId)] })
- queryClient.invalidateQueries({
- queryKey: ['webhook-endpoints', storeId, endpointId],
- })
+ queryClient.invalidateQueries({ queryKey: buildKey('webhook-deliveries', endpointId) })
+ queryClient.invalidateQueries({ queryKey: buildKey('webhook-endpoints', endpointId) })
},
})
}
export function useWebhookDelivery(endpointId: string | undefined, deliveryId: string | undefined) {
- const { storeId } = useStore()
return useQuery({
- queryKey: [
+ queryKey: useResourceKey(
'webhook-endpoints',
- storeId,
endpointId ?? 'noop',
'deliveries',
deliveryId ?? 'noop',
- ] as const,
+ ),
queryFn: () =>
adminClient.webhookEndpoints.deliveries.get(endpointId as string, deliveryId as string),
enabled: !!endpointId && !!deliveryId,
@@ -138,16 +106,14 @@ export function useWebhookDelivery(endpointId: string | undefined, deliveryId: s
}
export function useRedeliverWebhookDelivery(endpointId: string) {
- const { storeId } = useStore()
-
return useResourceMutation<WebhookDelivery, Error, string>({
mutationFn: (deliveryId) =>
adminClient.webhookEndpoints.deliveries.redeliver(endpointId, deliveryId),
invalidate: [
- // Same matching as send-test — the table prefix the ResourceTable
- // actually queries under, plus the endpoint's detail cache for totals.
- [webhookDeliveriesTableKey(endpointId)],
- ['webhook-endpoints', storeId, endpointId],
+ // The deliveries table queried via ResourceTable + the endpoint's
+ // detail cache (totals + last_delivery_at).
+ ['webhook-deliveries', endpointId],
+ ['webhook-endpoints', endpointId],
],
successMessage: false,
errorMessage: 'Failed to redeliver',
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/options.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/options.tsx
index 6ecfd13189..16bdb70cb0 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/options.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/options.tsx
@@ -78,7 +78,6 @@ import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import { z } from 'zod/v4'
import {
- optionTypesQueryKey,
useCreateOptionType,
useDeleteOptionType,
useOptionType,
@@ -176,7 +175,7 @@ function OptionTypesPage() {
reorder={{
onReorder: async (id, position) => {
await adminClient.optionTypes.update(id, { position })
- queryClient.invalidateQueries({ queryKey: optionTypesQueryKey })
+ queryClient.invalidateQueries({ queryKey: ['option-types'] })
},
}}
/>
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/markets.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/markets.tsx
index 3bbf958789..cac3442a31 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/markets.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/markets.tsx
@@ -38,13 +38,7 @@ import { useEffect, useMemo } from 'react'
import { Controller, type UseFormReturn, useForm } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import { z } from 'zod/v4'
-import {
- marketsQueryKey,
- useCreateMarket,
- useDeleteMarket,
- useMarket,
- useUpdateMarket,
-} from '@/hooks/use-markets'
+import { useCreateMarket, useDeleteMarket, useMarket, useUpdateMarket } from '@/hooks/use-markets'
import {
MARKET_DEFAULTS,
type MarketFormValues,
@@ -134,7 +128,7 @@ function MarketsPage() {
reorder={{
onReorder: async (id, position) => {
await adminClient.markets.update(id, { position })
- queryClient.invalidateQueries({ queryKey: marketsQueryKey })
+ queryClient.invalidateQueries({ queryKey: ['markets'] })
},
}}
/>
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/webhooks/$webhookEndpointId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/webhooks/$webhookEndpointId.tsx
index ec746f3041..0433eec18b 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/webhooks/$webhookEndpointId.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/webhooks/$webhookEndpointId.tsx
@@ -53,7 +53,6 @@ import {
useUpdateWebhookEndpoint,
useWebhookDelivery,
useWebhookEndpoint,
- webhookDeliveriesTableKey,
} from '@/hooks/use-webhook-endpoints'
import { webhookEndpointHealth, webhookHealthBadgeVariant } from '@/lib/webhook-health'
import {
@@ -411,10 +410,10 @@ function DeliveriesCard({
return (
<ResourceTable<WebhookDelivery>
tableKey="webhook-deliveries"
- // `webhookDeliveriesTableKey` keeps the table's prefix in sync with the
- // mutation invalidation in use-webhook-endpoints.ts — without that, the
- // new test/redeliver row never appears until a manual refresh.
- queryKey={webhookDeliveriesTableKey(endpointId)}
+ // Mutation hooks invalidate +['webhook-deliveries', endpointId]+ —
+ // ResourceTable auto-injects storeId between the two slots, so the
+ // prefix-match still fires across remounts.
+ queryKey={['webhook-deliveries', endpointId]}
queryFn={(params) => adminClient.webhookEndpoints.deliveries.list(endpointId, params)}
searchParams={searchParams}
/>