reactjsreact-hooksreact-apolloreact-apollo-hooksgraphql-tag

How to get useLazyQuery hooks data after calling a function


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?


Solution

  • 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 } });
      }
    }