【问题标题】:How I can make asynchronous queries in GraphQL?如何在 GraphQL 中进行异步查询?
【发布时间】:2021-04-23 06:06:49
【问题描述】:

我正在调用 1 个查询和突变。突变工作正常,但是当我从查询中获得响应时,我需要将用户重定向到另一个页面,但在我的情况下,该函数在我得到响应之前被触发。我怎样才能防止这种情况发生?

          const renderData = async () => {
            const currentUserId = await data?.signInUserSession?.idToken
              ?.payload?.sub;
            const isAdmin = await data?.signInUserSession?.idToken?.payload[
              "custom:role"
            ];
            localStorage.setItem("userId", currentUserId);

            if (
              currentUserId !== null &&
              currentUserId !== undefined &&
              currentUserId !== ""
            ) {
              Auth.currentSession().then((data) => {
                setData({
                  variables: {
                    updateUserInput: {
                      id: currentUserId,
                      firstName: data.getIdToken().payload.given_name,
                      lastName: data.getIdToken().payload.family_name,
                    },
                  },
                });
              });
              isCodeValid({
                variables: {
                  validateUserVerificationCodeInput: {
                    user: {
                      id: currentUserId,
                    },
                  },
                },
              });


              if (isAdmin === "admin" && isUserCodeValid) {
                history.push("/managements");
              } else if (
                isUserCodeValid !== undefined &&
                isUserCodeValid === true
              ) {
                history.push("/verification");
              } else if (isUserCodeValid) {
                history.push("/stripe");
              }
            }
          };
isUserCodeValid - is a response from query

【问题讨论】:

    标签: javascript reactjs graphql apollo


    【解决方案1】:

    对于这种情况,useMutation 具有 onCompleted 和 refetchQueries 选项。很难为您的案例编写一个精确的解决方案,因为并非所有代码都是可见的,但我相信下面的示例可以提供帮助:

    const [addProduct, { data, loading, error }] = useMutation(
        createProductMutation
      );
    
     const onFinish = async (fieldNames) => {  
      
        await addSpending({
          variables: { ...others, ...fieldNames},
          refetchQueries: [{ query: calledQuery }],
          onCompleted: (data) => {
             // your logic 
          },
        });
        if (!error) {
          form.resetFields();
          onFinishSave(true);
        }
      };
    

    【讨论】:

      猜你喜欢
      • 2020-06-01
      • 2023-03-19
      • 2020-02-18
      • 2014-04-24
      • 2020-05-23
      • 2022-11-25
      • 2018-12-11
      • 2021-09-16
      • 1970-01-01
      相关资源
      最近更新 更多