How to get useLazyQuery hooks data after calling a function

10.5k views Asked by At

I'm trying to to call useLazyQuery after submitting form/onClick, but for some reason I'm always getting undefined. Here is how I have defined my hook;

const component = () => {
 const [getMyValues, {loading, error, data: myValues}] = useLazyQuery(GET_MY_VALUES);
 
 onSubmit = async () => {
   if(checkCondition){
     const someData = await getMyValues({ variables: {o: names } });
     console.log({someData})    //undefined
   }
 }
}

How can I get the query data in someData variable?

2

There are 2 answers

0
chonnychu On BEST ANSWER

UPDATE:

Found a solution, but I haven't tried it, maybe you can give it a try. https://github.com/apollographql/react-apollo/issues/3499#issuecomment-539346982

useLazyQuery isn't return a promise, you should use onCompleted function parameter instead, like this:

const [getMyValues, {loading, error, data: myValues}] = useLazyQuery(GET_MY_VALUES, {
  onCompleted: someData => {
    console.log(someData)
    /* do your staff */
  }
});

// It's equal with someData 
// when `getMyValues` ​​is executed, the response data will be 
// return to `myValues`, so you can also use it.
React.useEffect(() => {
  console.log(myValues)
}, [myValues])
 
onSubmit = () => {
  if(checkCondition){
    getMyValues({ variables: {o: names } });
  }
}
2
Manuel Pamplona On

You need to rely on myValues from useLazyQuery.

So if you want to assign thew the result from the query to someData you'll need to do it like

const component = () => {
 const [getMyValues, {loading, error, data: myValues}] = useLazyQuery(GET_MY_VALUES);
 
 const someData = myValues;
 console.log({someData})
 onSubmit = () => {
   if(checkCondition){
     getMyValues({ variables: {o: names } });
   }
 }
}

So when getMyValues loads the result it will re-render the component and data will be available from myValues