Skip to content

Instantly share code, notes, and snippets.

@t3dotgg
Created February 2, 2024 06:12
Show Gist options
  • Save t3dotgg/b4383f607bf26b40e3e7e25e63e78ec9 to your computer and use it in GitHub Desktop.
Save t3dotgg/b4383f607bf26b40e3e7e25e63e78ec9 to your computer and use it in GitHub Desktop.
import { useQuery } from "@tanstack/react-query";
type Action<TActionInput = unknown, TActionReturn = unknown> = (
input: TActionInput,
) => Promise<TActionReturn>;
export type BundledAction<TAction extends Action> = {
key: string[];
result: Awaited<ReturnType<TAction>>;
action: TAction;
input: Parameters<TAction> extends undefined
? Parameters<TAction>
: undefined;
};
export async function bundleAction<TAction extends Action>(
...params: [
key: string[],
action: TAction,
...(Parameters<TAction> extends undefined ? [Parameters<TAction>] : []),
]
): Promise<BundledAction<TAction>> {
const [key, action, input] = params;
return {
key,
result: (await action(input)) as Awaited<ReturnType<TAction>>,
action,
input,
};
}
export function useActionQuery<TAction extends Action>(
bundle: BundledAction<TAction>,
optionalNewInput?: Parameters<TAction>,
) {
return useQuery({
queryKey: bundle.key,
queryFn: () =>
bundle.action(optionalNewInput ?? bundle.input) as Awaited<
ReturnType<TAction>
>,
initialData: bundle.result,
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment