I am using Apollo Client and the useLazyQuery hook to execute a query on mouse click. I am having a problem though that the data always returns null the first time I click. If I click the button again, the data comes back from the API. How can I make it so that I do not need to click the button twice to get the query response?
const [
fetchHacker,
{ loading: hackerLoading, error: hackerError, data: hackerData },
] = useLazyQuery<IHacker>(GETHACKER)
const [
fetchPartner,
{ loading: partnerLoading, error: partnerError, data: partnerData },
] = useLazyQuery<IPartner>(GETPARTNER)
const [
fetchMentor,
{ loading: mentorLoading, error: mentorError, data: mentorData },
] = useLazyQuery<IMentor>(GETHACKER)
const {
hacker,
setHacker,
partner,
setPartner,
mentor,
setMentor,
} = useGlobalContext()
const router = useRouter()
const handleClick = async (
e: React.MouseEvent<HTMLButtonElement, MouseEvent>,
): Promise<void> => {
e.preventDefault()
if (!email || !validateEmail(email)) {
setEmailError('Please enter a valid email address')
}
await fetchHacker({ variables: { email } })
await fetchPartner({ variables: { email } })
await fetchMentor({ variables: { email } })
if (!hackerLoading && hackerData) {
setHacker(hackerData.getHacker)
router.replace('/hacker-form')
} else if (!partnerLoading && partnerData) {
setPartner(partnerData.getPartner)
router.replace('/partner-form')
} else if (!mentorLoading && mentorData) {
setMentor(mentorData.getMentor)
router.replace('/mentor-form')
} else {
router.replace('/signup')
}
}
<button
type="submit"
className="hover:shadow-form rounded-md bg-[#6A64F1] py-3 px-8 text-base font-semibold text-white outline-none"
onClick={(e) => handleClick(e)}
>
Submit
</button>