TheEdoRan / next-safe-action

Type safe and validated Server Actions in your Next.js (App Router) project.

Home Page:https://next-safe-action.dev

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

`useAction` triggering stale callback functions unexpectedly due to outdated references

panchaow opened this issue · comments

Refs in the following lines of code always reference the callback functions initially passed instead of those passed in the most recent call because they never get updated.

const onExecuteRef = React.useRef(cb?.onExecute);
const onSuccessRef = React.useRef(cb?.onSuccess);
const onErrorRef = React.useRef(cb?.onError);
const onSettledRef = React.useRef(cb?.onSettled);

It this the expected behavior?

Callback functions don't change once you've passed them to useAction/useOptimisticAction hooks. If React.useRef is not used there, there is no guarantee that these callbacks will be executed only once. In fact, in my tests, they are executed multiple times. The arguments passed to the functions are updated in every call though, so if the action is re-executed, you'll get fresh data in callbacks. I'd say they work as expected. Did you find any bugs using them?