0

我试图在提交表单/onClick 后调用 useLazyQuery,但由于某种原因,我总是不确定。这是我定义我的钩子的方式;

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变量中的查询数据?

4

2 回答 2

3

更新:

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

useLazyQuery 不返回承诺,您应该改用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 } });
  }
}
于 2020-12-02T00:22:18.143 回答
0

您需要依赖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中可用

于 2020-12-02T00:16:16.323 回答