Getting value of Dispatch in React/Redux

Viewed 1610

I am trying to implement an account verification via the twilio api where it texts a user a code and it should set the state of generatedCode to that value, but i am having a difficult time getting that value of the dispatch. If i do a simple await with axios call it works fine, but not so much with a dispatch

action:

export const attemptRegisterVerify = (phone) => async (dispatch) => {
  dispatch(registerVerifyBegin());
  await postRegisterVerifyPhone(phone)
    .then((res) => {
      dispatch(registerVerifySuccess(res.data));
    })
    .catch((error) => {
      dispatch(registerVerifyFail(error));
    });
};

handleVerification:

const handleVerification = async (values) => {
    const { email, phone } = values;
    setModal(true);
    try {
      const response = await axios.post(
        'http://localhost:8000/api/v1/auth/register/check-duplicate',
        {
          email,
          phone,
        }
      );

      if (response.data.success) {
        switch (response.data.message) {
          case 0:
            try {
              const response = await dispatch(
                attemptRegisterVerify({ to: phone })
              );
              console.log(response);
              // if (response.data.success) {
              //   setGeneratedCode(response.data.message);
              //   console.log(generatedCode);
              // } else {
              //   console.log(response.data.message);
              // }
            } catch (error) {
              console.log(error);
            }
            break;

          case 1:
            console.log('Email Address already in use.');
            break;
          case 2:
            console.log('Phone number already in use.');
            break;
          case 3:
            console.log('Email and Phone in use.');
            break;
        }
      } else {
        console.log(response.data.message);
      }
    } catch (error) {
      console.log(error);
    }
  };

The console.log(response) returns undefined. Is there a way for it to wait until that dispatch is completed, then proceed?


export const attemptRegisterVerify = (phone) => async (dispatch) => {
  dispatch(registerVerifyBegin());
  await postRegisterVerifyPhone(phone)
    .then((res) => {
      dispatch(registerVerifySuccess(res.data));
      return res.data; // return console.log(res.data) works
    })
    .catch((error) => {
      dispatch(registerVerifyFail(error));
    });
};
1 Answers

Dispatch returns what you return in the function call. In the case of an async thunk, it'll return Promise<void> by default unless you return something.

If in your attemptRegisterVerify thunk, if you add return 'test' to the end of it, then your console.log(response) would log 'test'.

In a non-thunk, the return value of the dispatch would be the action that was generated.

Related