1 import {
2 MutationOptions,
3 QueryKey,
4 UseQueryOptions,
5 useMutation,
6 useQuery,
7 } from "@tanstack/react-query"
8
9 import { FetchError } from "@medusajs/js-sdk"
10 import { HttpTypes } from "@medusajs/types"
11 import { sdk } from "../../lib/client"
12 import { queryClient } from "../../lib/query-client"
13 import { queryKeysFactory } from "../../lib/query-key-factory"
14 import { pricePreferencesQueryKeys } from "./price-preferences"
15
16 const STORE_QUERY_KEY = "store" as const
17 export const storeQueryKeys = queryKeysFactory(STORE_QUERY_KEY)
18
19 /**
20 * Workaround to keep the V1 version of retrieving the store.
21 */
22 export async function retrieveActiveStore(
23 query?: HttpTypes.AdminStoreParams
24 ): Promise<HttpTypes.AdminStoreResponse> {
25 const response = await sdk.admin.store.list(query)
26
27 const activeStore = response.stores?.[0]
28
29 if (!activeStore) {
30 throw new FetchError("No active store found", "Not Found", 404)
31 }
32
33 return { store: activeStore }
34 }
35
36 export const useStore = (
37 query?: HttpTypes.SelectParams,
38 options?: Omit<
39 UseQueryOptions<
40 HttpTypes.AdminStoreResponse,
41 FetchError,
42 HttpTypes.AdminStoreResponse,
43 QueryKey
44 >,
45 "queryFn" | "queryKey"
46 >
47 ) => {
48 const { data, ...rest } = useQuery({
49 queryFn: () => retrieveActiveStore(query),
50 queryKey: storeQueryKeys.details(),
51 ...options,
52 })
53
54 return {
55 ...data,
56 ...rest,
57 }
58 }
59
60 export const useUpdateStore = (
61 id: string,
62 options?: MutationOptions<
63 HttpTypes.AdminStoreResponse,
64 FetchError,
65 HttpTypes.AdminUpdateStore
66 >
67 ) => {
68 return useMutation({
69 mutationFn: (payload) => sdk.admin.store.update(id, payload),
70 onSuccess: (data, variables, context) => {
71 queryClient.invalidateQueries({
72 queryKey: pricePreferencesQueryKeys.list(),
73 })
74 queryClient.invalidateQueries({
75 queryKey: pricePreferencesQueryKeys.details(),
76 })
77 queryClient.invalidateQueries({ queryKey: storeQueryKeys.details() })
78
79 options?.onSuccess?.(data, variables, context)
80 },
81 ...options,
82 })
83 }