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.

Changed country pickers to load the country list once (#14632)

Damian Legawiec67594a56921f
diff --git a/.changeset/cache-countries-list.md b/.changeset/cache-countries-list.md
new file mode 100644
index 0000000000..f7ac51fc6b
--- /dev/null
+++ b/.changeset/cache-countries-list.md
@@ -0,0 +1,7 @@
+---
+"@spree/dashboard-core": patch
+---
+
+Country pickers load the country list once per page and reuse it.
+
+The list is reference data and does not change at runtime, so later address fields and country selects no longer call the API again.
diff --git a/packages/dashboard-core/src/hooks/use-countries.test.ts b/packages/dashboard-core/src/hooks/use-countries.test.ts
new file mode 100644
index 0000000000..07c37025e8
--- /dev/null
+++ b/packages/dashboard-core/src/hooks/use-countries.test.ts
@@ -0,0 +1,56 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { type PanelApiClient, setApiClient } from '../api-client'
+import { loadCountries, resetCountriesCache } from './use-countries'
+
+function registerClient(listCountries?: PanelApiClient['listCountries']) {
+ setApiClient({ listCountries } as PanelApiClient)
+}
+
+afterEach(() => {
+ resetCountriesCache()
+})
+
+describe('loadCountries', () => {
+ it('calls the API once and reuses the stored list', async () => {
+ const data = [{ iso: 'US', iso3: 'USA', name: 'United States' }]
+ const listCountries = vi.fn().mockResolvedValue({ data })
+ registerClient(listCountries)
+
+ const first = await loadCountries()
+ const second = await loadCountries()
+
+ expect(listCountries).toHaveBeenCalledTimes(1)
+ expect(first).toBe(second)
+ expect(first.data).toEqual(data)
+ })
+
+ it('shares one in-flight request across overlapping callers', async () => {
+ let resolveList!: (value: { data: [] }) => void
+ const listCountries = vi.fn(
+ () =>
+ new Promise<{ data: [] }>((resolve) => {
+ resolveList = resolve
+ }),
+ )
+ registerClient(listCountries)
+
+ const first = loadCountries()
+ const second = loadCountries()
+ resolveList({ data: [] })
+
+ expect(await first).toBe(await second)
+ expect(listCountries).toHaveBeenCalledTimes(1)
+ })
+
+ it('retries after a failed load', async () => {
+ const listCountries = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('network'))
+ .mockResolvedValueOnce({ data: [] })
+ registerClient(listCountries)
+
+ await expect(loadCountries()).rejects.toThrow('network')
+ await expect(loadCountries()).resolves.toEqual({ data: [] })
+ expect(listCountries).toHaveBeenCalledTimes(2)
+ })
+})
diff --git a/packages/dashboard-core/src/hooks/use-countries.ts b/packages/dashboard-core/src/hooks/use-countries.ts
index bebe5acdb7..9fef7916da 100644
--- a/packages/dashboard-core/src/hooks/use-countries.ts
+++ b/packages/dashboard-core/src/hooks/use-countries.ts
@@ -1,6 +1,44 @@
import { useQuery } from '@tanstack/react-query'
import { getApiClient, type PanelCountry } from '../api-client'
+/**
+ * One process-wide load of the country table.
+ *
+ * Countries are reference data — the same ~250 rows for every store, every
+ * panel, every session — so the first successful fetch is reused for the
+ * rest of the page. React Query's cache alone is not enough: it is dropped
+ * when the last picker unmounts (`gcTime`) and wiped on logout
+ * (`queryClient.clear()`), which is why a country field on every sheet was
+ * hitting the API again.
+ *
+ * A failed load is not stored, so the next picker can retry.
+ */
+let countriesRequest: Promise<{ data: PanelCountry[] }> | null = null
+
+/**
+ * The country list, loaded at most once per page. Subsequent callers share
+ * the same in-flight or resolved promise.
+ *
+ * @returns The panel's country payload (`{ data }`).
+ */
+export function loadCountries(): Promise<{ data: PanelCountry[] }> {
+ if (!countriesRequest) {
+ countriesRequest = (getApiClient().listCountries?.() ?? Promise.resolve({ data: [] })).catch(
+ (error: unknown) => {
+ countriesRequest = null
+ throw error
+ },
+ )
+ }
+
+ return countriesRequest
+}
+
+/** Drops the stored country list so the next read hits the API. For tests. */
+export function resetCountriesCache(): void {
+ countriesRequest = null
+}
+
/**
* Countries for the shared address form, through the registered panel client.
*
@@ -12,8 +50,9 @@ import { getApiClient, type PanelCountry } from '../api-client'
export function useCountries() {
const { data, isLoading } = useQuery({
queryKey: ['countries'],
- queryFn: () => getApiClient().listCountries?.() ?? Promise.resolve({ data: [] }),
- staleTime: 1000 * 60 * 30, // 30 minutes — countries rarely change
+ queryFn: loadCountries,
+ staleTime: Number.POSITIVE_INFINITY,
+ gcTime: Number.POSITIVE_INFINITY,
})
const countries: PanelCountry[] = data?.data ?? []