feat(dashboard): Update v2 store domain to follow conventions, and abstract some logic (#6927)
**What** - Updates the V2 store domain. - Abstracts some of the API requests logic into re-usable hooks **Note** - Partial PR as we need to add support for setting a default currency, region and location. Currently the `q` param is missing on all V2 endpoints, so we can't use our combobox component to list these options. Will be added later when that has been fixed in core. - The PR includes a generic hook for fetching combobox data, that I added before realising that `q` is not currently supported. But keeping it as it will be useful once support is added.
This commit is contained in:
committed by
GitHub
parent
3044ecaf61
commit
7385a67dc7
@@ -0,0 +1,71 @@
|
||||
import { QueryKey, useInfiniteQuery } from "@tanstack/react-query"
|
||||
import debounce from "lodash/debounce"
|
||||
import { useCallback, useEffect, useState } from "react"
|
||||
|
||||
type Params = {
|
||||
q: string
|
||||
limit: number
|
||||
offset: number
|
||||
}
|
||||
|
||||
type Page = {
|
||||
count: number
|
||||
offset: number
|
||||
limit: number
|
||||
}
|
||||
|
||||
type UseComboboxDataProps<TParams extends Params, TRes extends Page> = {
|
||||
fetcher: (params: TParams) => Promise<TRes>
|
||||
params?: Omit<TParams, "q" | "limit" | "offset">
|
||||
queryKey: QueryKey
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for fetching infinite data for a combobox.
|
||||
*/
|
||||
export const useComboboxData = <TParams extends Params, TRes extends Page>({
|
||||
fetcher,
|
||||
params,
|
||||
queryKey,
|
||||
}: UseComboboxDataProps<TParams, TRes>) => {
|
||||
const [query, setQuery] = useState("")
|
||||
const [debouncedQuery, setDebouncedQuery] = useState("")
|
||||
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
const debouncedUpdate = useCallback(
|
||||
debounce((query) => setDebouncedQuery(query), 300),
|
||||
[]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
debouncedUpdate(query)
|
||||
|
||||
return () => debouncedUpdate.cancel()
|
||||
}, [query, debouncedUpdate])
|
||||
|
||||
const data = useInfiniteQuery(
|
||||
[...queryKey, debouncedQuery],
|
||||
async ({ pageParam = 0 }) => {
|
||||
const res = await fetcher({
|
||||
q: debouncedQuery,
|
||||
limit: 10,
|
||||
offset: pageParam,
|
||||
...params,
|
||||
} as TParams)
|
||||
return res
|
||||
},
|
||||
{
|
||||
getNextPageParam: (lastPage) => {
|
||||
const morePages = lastPage.count > lastPage.offset + lastPage.limit
|
||||
return morePages ? lastPage.offset + lastPage.limit : undefined
|
||||
},
|
||||
keepPreviousData: true,
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
...data,
|
||||
query,
|
||||
setQuery,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user