'Why is my query called over and over using useLazyQuery? Apollo Hooks
I am using the useLazyQuery
hook from Apollo and get in an infinite loop. Here is my component:
import styled from 'styled-components'
import { useLazyQuery } from "@apollo/react-hooks"
import GENERATE_EFT_REFERENCE_NUMBER from "./graphql/generate-eft-reference-number.graphql"
let Link = styled.a`
color: ${props => props.theme.color.turquoise500};
cursor: pointer;
text-decoration: underline;
`
const GenerateEftReferenceLink = ({
externalAccountId,
financialMethodId,
internalAccountId,
highestReferenceNumber,
methodId,
updateMethod
}) => {
const [generateEftReference = {}, { called, loading, data }] = useLazyQuery(
GENERATE_EFT_REFERENCE_NUMBER,
{
variables: {
externalAccountId,
financialMethodId,
internalAccountId,
highestReferenceNumber
},
onCompleted: ({ generateEftReferenceNumber: reconciliationSerialNumber }) => {
updateMethod({ reconciliationSerialNumber }, methodId)
}
}
)
return <Link onClick={generateEftReference}>Click Me</Link>
}
export default GenerateEftReferenceLink
In the onCompleted
option, I take the result and use a callback (updateMethod
) to update my object.
The issue I am having is that the query gets called over and over. I hit the onCompleted
each time, which calls updateMethod
and I stay in this infinite loop. The onClick
is only being called when the Link
is clicked (I verified that by putting a debugger
in the onClick
), so this must be something to do with the useLazyQuery
hook.
I fixed this by changing to use the ApolloConsumer
component, but I want to understand why I get in this state with the hook.
Any ideas?
Solution 1:[1]
This was a bug in Apollo, they fixed it in @apollo/react-hooks v3.1.3 See this
Solution 2:[2]
I had the same problem but with useQuery
hook, and I was not able to update the library to the latest version, which will cause some side effects in my project, so I solved it in this way, mine while I update the lib.
onCompleted: useCallback(() => {//your code}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Yash |
Solution 2 | apaternina |