-
-
Notifications
You must be signed in to change notification settings - Fork 42
Description
Are you using the latest version of this library?
- I verified that the issue exists in the latest next-safe-action release
Is there an existing issue for this?
- I have searched the existing issues and found nothing that matches
Describe the bug
When the action redirects, onError
callback from useAction
parameter will be called again if it was called previously.
This can cause incorrect repeat notifications of stale errors.
I have a form component that does something like this:
const { executeAsync, status } = useAction(myAction, {
onError: ({ error }) => {
toast(error);
},
});
// this is react-hook-form, but shouln't matter
const onSubmit = form.handleSubmit(executeAsync);
...
And an action that can fail based on the form data. When the action succeeds, it calls redirect(...)
.
The problem is: if the action is called once and resulted in an error, and then it's called again with the correct data, then on the second call onError
will be called again, and there'll be an extra confusing toast for that older error.
I tried to trace this issue through the codebase, and in my understanding it's caused by this code:
next-safe-action/packages/next-safe-action/src/hooks.ts
Lines 54 to 58 in dc120df
safeActionFn(input as S extends Schema ? InferIn<S> : undefined) | |
.then((res) => setResult(res ?? {})) | |
.catch((e) => { | |
throw e; | |
}) |
When catch((e) => ...
happens because of NEXT_REDIRECT
, the result
is not reset, so it stays in "hasErrored"
state, and then the effect in useActionCallbacks()
fires once again with that stale errored result (for some reason; I'm not sure which effect dep causes the callbacks effect to fire).
Reproduction steps
- Start the https://github.com/berekuk/next-safe-action-redirect-error
- Press "fail".
- Check console; there will be the first "ERROR" in logs.
- Press "redirect"; see how there's a second "ERROR" being logged on redirect.
Expected behavior
On the second button click, onError
shouldn't be called.
Link to a minimal reproduction of the issue
https://github.com/berekuk/next-safe-action-redirect-error
Operating System
macOS
Library version
7.9.9
Next.js version
15.0.3
Node.js version
v20.15.1
Additional context
No response