简体   繁体   中英

How I can make asynchronous queries in GraphQL?

I'm calling 1 query and mutation. Mutation works fine, but when I get response from my query I need to redirect user to another page, but In my case, the function is triggered before I get response. How can I prevent this?

          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

useMutation has onCompleted and refetchQueries options for such cases. It is hard to write an exact solution for your case since not all code is visible but an example like below can help, I believe:

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

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