Skip to content

Instantly share code, notes, and snippets.

@dbarjs
Last active October 1, 2023 20:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dbarjs/e21a6ed49babe99ded84c4fe7b9403d6 to your computer and use it in GitHub Desktop.
Save dbarjs/e21a6ed49babe99ded84c4fe7b9403d6 to your computer and use it in GitHub Desktop.
usePersistentQuery - a @vueuse composable proposal
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;
}
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;
}
@dbarjs
Copy link
Author

dbarjs commented Oct 1, 2023

For now, I test only with Playwright. However, I need to develop the unit test to create the PR for vueuse.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment