1

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?

iCodeByte
  • 571
  • 1
  • 7
  • 21

2 Answers2

6

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 } });
  }
}
chonnychu
  • 1,068
  • 6
  • 10
-1

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

Manuel Pamplona
  • 217
  • 1
  • 5
  • Is there a way to use .then() after getMyValues() is called? I have tried using that but get an error. – iCodeByte Dec 02 '20 at 00:22
  • As is mentioned here https://stackoverflow.com/a/65100511/6051401 getMyValues isn't actually a promise. So you can't call neither then or awaiting for the response – Manuel Pamplona Dec 02 '20 at 00:41