Created
February 2, 2024 06:12
-
-
Save t3dotgg/b4383f607bf26b40e3e7e25e63e78ec9 to your computer and use it in GitHub Desktop.
This file contains 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 { 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