Dispatching action inside isError causing infinite rendering of isError #2598
-
I'm using React-Query with Redux Toolkit and Axios I'm trying to record the number of failed login attempts to the global state (redux) so I can show a recaptcha after XY failed login attempts. Using a useMutation hook to sign the user in. When there is a login error I want to dispatch an action to increment the number of failed login attempts in redux. Putting the dispatch inside isError is causing isError and the dispatch call to be infinitely. When the dispatch call is removed from isError, then isError is only called once as expected. I've created a sandbox and still cannot get a dispatch to be ran inside an isError |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Instead of calling
The reason: reference of data changes ->useSelector function returns you a new value-> re-renders the component->isError is still true -> dispatch is called agin 🔄 onError is called once - after mutation return error. There is also reset function from useMutation - but I don't test it in this case. |
Beta Was this translation helpful? Give feedback.
Instead of calling
useDispatch
in if withisError
, pass it toonError
callback.const { mutate, data, error, isError, isSuccess } = useMutation( (val) => signIn(val), { onError: () => dispatch(addAttempt()) } );
The reason: reference of data changes ->useSelector function returns you a new value-> re-renders the component->isError is still true -> dispatch is called agin 🔄
onError is called once - after mutation return error.
There is also reset function from useMutation - but I don't test it in this case.