Reputation: 974
I'm trying to build a form that could be used for any CRUD operation on a table. For the update operation I'd like to pass the variable with the route. All of that is working fine but when I call the query using a lazy query it does nothing for the first couple of calls and then returns the data on the third call. Is that normal? Am I calling the query wrong? Is there a way to wait for the query to return with the data?
import React, { useState, useEffect } from "react";
import Router, { useRouter } from "next/router";
import Container from "react-bootstrap/Container";
import { useLazyQuery } from "@apollo/react-hooks";
import { GET_PLATFORM } from "../graphql/platforms";
export default function platformsForm(props) {
const router = useRouter();
// grab the action requested by caller and the item to be updated (if applicable)
const [formAction, setFormAction] = useState(router.query.action);
const [formUpdateId, setFormUpdateId] = useState(router.query.id);
const [
getPlatformQuery,
{ loading, error, data: dataGet, refetch, called }
] = useLazyQuery(GET_PLATFORM, {
variables: { id: formUpdateId }
});
useEffect(() => {
console.log("update");
// var dataReturned = getPlatformLookup(formUpdateId);
!called && getPlatformQuery({ variables: { id: formUpdateId } });
if (dataGet && dataGet.Platform.platformName) {
console.log(
dataGet.Platform.platformName,
dataGet.Platform.platformCategory
);
}
}),
[];
return (
<Container>
<h4>
Name: {dataGet && dataGet.Platform.platformName}
<br />
Cat: {dataGet && dataGet.Platform.platformCategory}
<br />
formAction: {formAction}
<br />
formUpdateId: {formUpdateId}
<br />
</h4>
</Container>
);
}
Upvotes: 4
Views: 3925
Reputation: 4817
For calling useLazyQuery, you need to use useEffect
and pass empty array []
so you can call the query exactly once, which you have done already in your code (there is syntax error in your useEffect, )
missing).
Also, you cannot use the data (dataGet
)returned from the lazyQuery from inside of your useEffect callback.
You should do something like this:
// this useEffect hook will call your lazy query exactly once
useEffect(() => {
getPlatformQuery({ variables: { id: formUpdateId } });
}, []);
// you can fetch your data here (outside of the useEffect Hook)
if (dataGet && dataGet.Platform.platformName) {
console.log(
dataGet.Platform.platformName,
dataGet.Platform.platformCategory
);
}
return(<Container>
<h4>
Name: {dataGet && dataGet.Platform.platformName}
<br />
Cat: {dataGet && dataGet.Platform.platformCategory}
<br />
formAction: {formAction}
<br />
formUpdateId: {formUpdateId}
<br />
</h4>
</Container>);
Upvotes: 2