npm i @joeyfigaro/use-mutation-redirect
pnpm add @joeyfigaro/use-mutation-redirect
yarn add @joeyfigaro/use-mutation-redirect
react
+react-dom
v18.*
@tanstack/react-query
v5.*
(created using v5.69.0)
I plan to offer support for older versions of React and RQ (TQ?)
- import
useMutationRedirect
- use it in place of
useMutation
- provide options for
useMutation
as the first argument, andUseMutationRedirectOptions
as the second
import { useState } from 'react';
import { useMutationRedirect } from '@joeyfigaro/use-mutation-redirect';
import { useNavigate } from 'react-router-dom';
const Login = () => {
const [username, setUsername] = useState();
const [password, setPassword] = useState();
const navigate = useNavigate();
const authenticate = useMutationRedirect(
{
mutationFn: async () => {
try {
// handle your fetching...
} catch (error) {
throw new AuthenticationError(error);
}
},
retry: 3,
},
{
to: '/forgot-password',
navigateFn: navigate,
// redirect user to forgot password view if a mutation fails 3 times
trigger: (mutation) => mutation.isError && mutation.failureCount >= 3,
},
);
return (
<button onClick={() => authenticate.mutate({ username, password })}>
Authenticate
</button>
);
};
I got tired of rewriting the same post-mutation redirect logic over and over and over.
MIT © joeyfigaro