When I redirect to another page after a mutation, it shows memory leak warning. I tried many ways but I haven't found any solution.
The warning is:
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
CodePudding user response:
We can use useEffect
hook to redirect to another page after completing rerender. Here I found a solution using custom hook:
import { UseMutationResult } from '@tanstack/react-query';
import { useEffect } from 'react';
import { To, useNavigate } from 'react-router-dom';
export const useRedirectAfterMutation = <T, U>({
mutation,
navigateTo,
}: {
mutation: UseMutationResult<T, Error, U, unknown>;
navigateTo: To;
}) => {
const navigate = useNavigate();
useEffect(() => {
if (mutation.isSuccess && !!navigateTo) {
navigate(navigateTo);
}
}, [mutation.isSuccess, navigate, navigateTo]);
return mutation.mutateAsync;
};
const App = () => {
const createCategoryMutation = useCreateCategoryMutation();
const createCategoryMutate = useRedirectAfterMutation({
mutation: createCategoryMutation,
navigateTo: 'url',
});
return (
<div>
<button onClick={() => {
createCategoryMutate()
}}>redirect after mutation</button>
</div>
)
}
CodePudding user response:
You can use useMutation hook and then in the options use onSuccess option to navigate.
const navigate = useNavigate();
const { mutate } = useMutation((log) => console.log)
mutate('mutating', {
onSuccess: () => {
navigate('/url') //your url
},
})