简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM