Skip to content

Commit 9fe55a5

Browse files
feat: useToastMutation hook (#183)
* feat: useKbdShortcuts hook & example implementation * chore: tidy up remnant * feat: useToastMutation hook * chore: remove junk comment
1 parent 0d935a3 commit 9fe55a5

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

src/hooks/use-toast-mutation.ts

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import { toast } from "@stacklok/ui-kit";
2+
import {
3+
DefaultError,
4+
useMutation,
5+
UseMutationOptions,
6+
} from "@tanstack/react-query";
7+
import { useCallback } from "react";
8+
9+
export function useToastMutation<
10+
TData = unknown,
11+
TError = DefaultError,
12+
TVariables = void,
13+
TContext = unknown,
14+
>(options: UseMutationOptions<TData, TError, TVariables, TContext>) {
15+
const {
16+
mutateAsync: originalMutateAsync,
17+
// NOTE: We are not allowing direct use of the `mutate` (sync) function.
18+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
19+
mutate: _,
20+
...rest
21+
} = useMutation(options);
22+
23+
const mutateAsync = useCallback(
24+
<TError extends { detail: string | undefined }>(
25+
variables: Parameters<typeof originalMutateAsync>[0],
26+
options: Parameters<typeof originalMutateAsync>[1],
27+
{ successMsg }: { successMsg: string },
28+
) => {
29+
const promise = originalMutateAsync(variables, options);
30+
31+
toast.promise(promise, {
32+
success: successMsg,
33+
error: (e: TError) => (e.detail ? e.detail : "An error occurred"),
34+
});
35+
},
36+
[originalMutateAsync],
37+
);
38+
39+
return { mutateAsync, ...rest };
40+
}

0 commit comments

Comments
 (0)