如何在调用函数后获取 useLazyQuery 挂钩数据

How to get useLazyQuery hooks data after calling a function

我试图在提交后调用 useLazyQuery form/onClick,但由于某些原因,我总是无法定义。这是我定义钩子的方式;

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

如何获取someData变量中的查询数据?

您需要依赖 useLazyQuery 中的 myValues

因此,如果您想将查询的结果分配给 someData,您需要像这样

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

因此,当 getMyValues 加载结果时,它将重新渲染组件,并且数据将从 myValues

获得

更新:

找到了解决办法,但我没有试过,也许你可以试一试。 https://github.com/apollographql/react-apollo/issues/3499#issuecomment-539346982

useLazyQuery 不是 return 承诺,您应该改用 onCompleted 函数参数,如下所示:

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