[BUG] onError
called on redirects if it was called previously
#303
Labels
bug
Something isn't working
onError
called on redirects if it was called previously
#303
Are you using the latest version of this library?
Is there an existing issue for this?
Describe the bug
When the action redirects,
onError
callback fromuseAction
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:
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
When
catch((e) => ...
happens because ofNEXT_REDIRECT
, theresult
is not reset, so it stays in"hasErrored"
state, and then the effect inuseActionCallbacks()
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
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
The text was updated successfully, but these errors were encountered: