Skip to content

Commit

Permalink
feat(query): add 'useQueriesState' composable (wip)
Browse files Browse the repository at this point in the history
  • Loading branch information
ElisePatrikainen committed Apr 28, 2024
1 parent 78345fa commit 25a237f
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 2 deletions.
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export {
serialize,
type UseQueryEntry,
} from './query-store'
export { useQueriesState } from './use-queries-state'

export { TreeMapNode, type EntryNodeKey } from './tree-map'

Expand Down
4 changes: 2 additions & 2 deletions src/query-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ export const useQueryCache = defineStore(QUERY_STORE_ID, () => {

function ensureEntry<TResult = unknown, TError = ErrorDefault>(
keyRaw: EntryKey,
options: UseQueryOptionsWithDefaults<TResult, TError>,
options?: UseQueryOptionsWithDefaults<TResult, TError>,
): UseQueryEntry<TResult, TError> {
if (process.env.NODE_ENV !== 'production' && keyRaw.length === 0) {
throw new Error(
Expand All @@ -188,7 +188,7 @@ export const useQueryCache = defineStore(QUERY_STORE_ID, () => {
cachesRaw.set(
key,
(entry = scope.run(() =>
createQueryEntry(key, options.initialData?.()),
createQueryEntry(key, options?.initialData?.()),
)!),
)
}
Expand Down
31 changes: 31 additions & 0 deletions src/use-queries-state.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import type { MaybeRefOrGetter } from 'vue'
import { computed, toValue } from 'vue'
import type { EntryKey } from './entry-options'
import type { QueryStatus } from './query-store'
import { useQueryCache } from './query-store'

interface QueryState {
data: unknown
error: unknown
status: QueryStatus
}

// TODO: accept also a since key (instead of an array) as argument
// TODO: accept a ref for `keys` (to handle adding/removing entries for example)?
export function useQueriesState(keys: Array<MaybeRefOrGetter<EntryKey>>) {
const { ensureEntry } = useQueryCache()
return computed(() => {
return keys.map<QueryState[]>(
// TODO: fix TS issue
(key) => {
const query = ensureEntry(toValue(key))
return {
data: query.data.value,
error: query.error.value,
status: query.status.value,
options: query.options,
}
},
)
})
}

0 comments on commit 25a237f

Please sign in to comment.