Last active
October 1, 2023 20:15
-
-
Save dbarjs/e21a6ed49babe99ded84c4fe7b9403d6 to your computer and use it in GitHub Desktop.
usePersistentQuery - a @vueuse composable proposal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import type { TupleToUnion } from 'type-fest'; | |
import type { UsePersistentQueryOptions } from './usePersistentQuery'; | |
import { usePersistentQuery } from './usePersistentQuery'; | |
import { useRoute } from '#vue-router'; | |
export function usePersistentQueries< | |
TKeys extends readonly string[], | |
TReturn = Record<TupleToUnion<TKeys>, Ref<string>>, | |
>(keys: TKeys, options: UsePersistentQueryOptions = {}): TReturn { | |
options.route = options.route || useRoute(); | |
return keys.reduce( | |
(queries, queryKey) => { | |
queries[queryKey] = usePersistentQuery(queryKey, options); | |
return queries; | |
}, | |
{} as Record<string, Ref<string>>, | |
) as TReturn; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useSessionStorage, useLocalStorage, syncRef } from '@vueuse/core'; | |
import { useRouteQuery } from '@vueuse/router'; | |
import type { RouteLocationNormalizedLoaded } from '#vue-router'; | |
export interface UsePersistentQueryOptions { | |
isSessionOnly?: boolean; | |
route?: RouteLocationNormalizedLoaded; | |
customKeyPrefix?: string; | |
} | |
function getQueryOnStorage( | |
queryKey: string, | |
isSessionOnly?: boolean, | |
): Ref<string> { | |
if (isSessionOnly) { | |
return useSessionStorage(queryKey, ''); | |
} | |
return useLocalStorage(queryKey, ''); | |
} | |
export function usePersistentQuery( | |
queryKey: string, | |
options: UsePersistentQueryOptions, | |
): Ref<string> { | |
const { route = useRoute() } = options; | |
const storageRef = getQueryOnStorage(queryKey, options.isSessionOnly); | |
const routeRef = useRouteQuery(queryKey, '', { | |
mode: 'replace', | |
route, | |
transform: (value) => { | |
return value?.toString() ?? ''; | |
}, | |
}); | |
storageRef.value = routeRef.value || storageRef.value; | |
syncRef(storageRef, routeRef); | |
return routeRef; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For now, I test only with Playwright. However, I need to develop the unit test to create the PR for vueuse.