react-apollo-hooks
react-apollo-hooks copied to clipboard
Calling a mutation within React.useEffect causes infinite loop
I'm attempting to perform a mutation when a specific route is hit in my application. When using useEffect and passing through a mutation method as a dependancy, it enters an infinite loop.
const [myMutation] = useMutation(MY_MUTATION);
const Component = () => {
React.useEffect(() => {
myMutation();
}, [myMutation]);
}
This may be by design and my code an anti-pattern, if so I'd love to know an alternative way to trigger a mutation when a component is mounted for the first time.
A similar issue was fixed in graphql-hooks
recently, if that helps at all.
I seems it enters an infinite loop because of "myMutation" in the useEffect second argument. It happens because every time that a mutation calls, returned function "myMutation" also changes. Did you try it without that argument ? I know it causes a warning, but maybe it'll fix your problem. Anyway, if you find your answer, let us know. I started a react apollo project recently and glad to know all about it.
Yeah whilst that does fix the problem, unfortunately that goes against the official spec for useEffect and breaks hook linting. I'd like to find a way to fix this without having to disable the linter for that line.
Did you found a way to solve this issue? Is there a reason for myMutation
to change every time it's called? I agree that this looks strange to omit it from the dependency list, I would also like to avoid this.
Yes, your suggestions do fix the problem but give the lint warning. But the proper way of doing this is to destructure the mutate from the mutation and provide that to the dependency array of use effect!
const {mutate} = useMutation(someFunction)
useEffect(() => { mutate() }, [mutate])
Omg thank you @yaralahruthik! This solved my identical issue perfectly without requiring weird workarounds :)
I am also getting an infinite loop and i am using useMutation from '@tanstack/react-query';
const { mutate, data: fetchedUsers, isLoading: isLoadingUsers, error, isError: isLoadingUsersError, }: any = useMutation({ mutationFn: () => useUserMutation(USERS_KEY, countyid, token), mutationKey: ['userslist'], retry: false, });
useEffect(() => { mutate(); }, []);
I am also getting an infinite loop and i am using useMutation from '@tanstack/react-query';
const { mutate, data: fetchedUsers, isLoading: isLoadingUsers, error, isError: isLoadingUsersError, }: any = useMutation({ mutationFn: () => useUserMutation(USERS_KEY, countyid, token), mutationKey: ['userslist'], retry: false, });
useEffect(() => { mutate(); }, []);
In your case the issue does not seem to be in this part of the code. Is it possible that the mutation updates some data which results in re-rendering the component that calls it? Maybe try commenting out parts of code to figure the actual cause?
Weird API. You end up having to rename mutate and mutateAsync every time in order to get this right.