Call asynchronous function

Asked

Viewed 83 times

0

I have the function:

const sendSMS = () => {
    return async (dispatch, getState, api) => {
        dispatch({ type: SEND_CODE });
        const { phoneNumber } = getState().AuthReducer;
        try {
            const response = await api({ noAuth: true }).post('communication/sms_token', { mobile_phone: phoneNumber });
            dispatch({ type: SENT_SUCCESS });
            Reactotron.log(response);
        }
        catch (err) {
            dispatch({ type: SENT_ERROR, payload: 'Erro ao enviar SMS, tente novamente' });
            Reactotron.log(err);
        }
    }
}

I want to call this function inside the Register function:

export const register = () => {
    return async (dispatch, getState, api) => {
        dispatch({ type: REGISTER });

        const { phoneNumber, countryCode } = getState().AuthReducer;
        const { fullName, email, birthdate, gender, city } = getState().UserReducer;
        const { mac } = getState().SystemReducer;
        const token = generateToken();
        const date = moment().format('YYYY-MM-DD HH:mm:ss');

        const accountObj = {
            user: {
                nome: fullName,
                email: email,
                ddi: countryCode,
                ddd: phoneNumber.slice(0, 2),
                celular: phoneNumber,
                sexo: gender,
                nascimento: moment(birthdate).format('YYYY-MM-DD'),
                cidade: city,
                local: 59,
                token: token,
                ultima_mensagem: date,
                ultima_mensagem_ios: date,
                ultima_mensagem_android: date,
                email_novidades: 0
            },
            device: {
                platform: Platform.OS,
                mac: mac,
                data: date
            }
        }

        //Register
        try {
            const response = await api({ noAuth: true }).post('users', accountObj);
            dispatch({ type: REGISTER_FINISH });
            dispatch({ type: SYSTEM_CHANGE_ID, payload: response.data.user.id_u });
            dispatch({ type: USER_CHANGE_ID, payload: response.data.device.id_d });
            await sendSMS();
        }
        catch (err) {
            dispatch({ type: REGISTER_ERROR });
        }
    }
}

The sendSMS function is never called although the Register function does not fall in catch. No error occurs during runtime, it is as if the function was never called.

  • face think your error is simple try this await sendSMS()(); Its function returns a function so it must execute the return and then yes wait the flow with the await.

  • 1

    Vlw by suggestion but actually found that I needed to use Dispatch to call the function: Dispatch(sendSMS());

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.