Skip to content

Commit

Permalink
feat(hooks): add onSettled callback
Browse files Browse the repository at this point in the history
  • Loading branch information
TheEdoRan committed Oct 3, 2023
1 parent 232d2ac commit 60c14aa
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 0 deletions.
6 changes: 6 additions & 0 deletions packages/example-app/src/app/hook/deleteuser-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ const DeleteUserForm = ({ userId, deleteUser }: Props) => {
// You can reset result object by calling `reset`.
// reset();
},
onSettled(result, input, reset) {
console.log("HELLO FROM ONSETTLED", result, input);

// You can reset result object by calling `reset`.
// reset();
},
onExecute(input) {
console.log("HELLO FROM ONEXECUTE", input);
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@ const AddLikesForm = ({ likesCount, addLikes }: Props) => {
// You can reset result object by calling `reset`.
// reset();
},
onSettled(result, input, reset) {
console.log("HELLO FROM ONSETTLED", result, input);

// You can reset result object by calling `reset`.
// reset();
},
onExecute(input) {
console.log("HELLO FROM ONEXECUTE", input);
},
Expand Down
4 changes: 4 additions & 0 deletions packages/next-safe-action/src/hook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,14 @@ const useActionCallbacks = <const Schema extends z.ZodTypeAny, const Data>(
const onExecuteRef = useRef(cb?.onExecute);
const onSuccessRef = useRef(cb?.onSuccess);
const onErrorRef = useRef(cb?.onError);
const onSettledRef = useRef(cb?.onSettled);

// Execute the callback on success or error, if provided.
useEffect(() => {
const onExecute = onExecuteRef.current;
const onSuccess = onSuccessRef.current;
const onError = onErrorRef.current;
const onSettled = onSettledRef.current;

const executeCallbacks = async () => {
switch (status) {
Expand All @@ -58,9 +60,11 @@ const useActionCallbacks = <const Schema extends z.ZodTypeAny, const Data>(
break;
case "hasSucceded":
await Promise.resolve(onSuccess?.(result.data!, input, reset));
await Promise.resolve(onSettled?.(result, input, reset));
break;
case "hasErrored":
await Promise.resolve(onError?.(result, input, reset));
await Promise.resolve(onSettled?.(result, input, reset));
break;
}
};
Expand Down
5 changes: 5 additions & 0 deletions packages/next-safe-action/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,11 @@ export type HookCallbacks<Schema extends z.ZodTypeAny, Data> = {
input: z.input<Schema>,
reset: () => void
) => MaybePromise<void>;
onSettled?: (
result: HookResult<Schema, Data>,
input: z.input<Schema>,
reset: () => void
) => MaybePromise<void>;
};

/**
Expand Down

0 comments on commit 60c14aa

Please sign in to comment.