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

iCo*_*yte 1 reactjs react-apollo graphql-tag react-hooks react-apollo-hooks

我试图在提交表单/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
   }
 }
}
Run Code Online (Sandbox Code Playgroud)

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

cho*_*chu 6

更新:

\n

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

\n

useLazyQuery 不返回承诺,您应该使用onCompleted函数参数,如下所示:

\n
const [getMyValues, {loading, error, data: myValues}] = useLazyQuery(GET_MY_VALUES, {\n  onCompleted: someData => {\n    console.log(someData)\n    /* do your staff */\n  }\n});\n\n// It\'s equal with someData \n// when `getMyValues` \xe2\x80\x8b\xe2\x80\x8bis executed, the response data will be \n// return to `myValues`, so you can also use it.\nReact.useEffect(() => {\n  console.log(myValues)\n}, [myValues])\n \nonSubmit = () => {\n  if(checkCondition){\n    getMyValues({ variables: {o: names } });\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n