How to handle conditions after asynchronous request

73 Views Asked by At

Thanks for reading my question in advance. I'm using the dva and Ant Design Mobile of React handling phone register function.

Before sending the verify code, I will judge if the phone has been registered. If yes, it will Toast " This phone has been registered".

Now, the return value is correct:

const mapStateToProps = (state) => {
  console.log(state.register.message)
}
// {code: 221, message: "This phone has been registered"}

So I write it as:

const mapStateToProps = (state) => ({
  returnData: state.register.message
})

And then when I click the button, it will dispatch an action (send a request):

  getVerifyCode() {
    const { form, returnData } = this.props;
    const { getFieldsValue } = form;
    const values = getFieldsValue();
    this.props.dispatcher.register.send({
        phone: values.phone,
        purpose: 'register',
      })
      // if(returnData.code === 221){
      //   Toast.fail("This phone has been registered", 1);
      // } else {
      //   Toast.success("Send verify code successfully", 1);
      // }
  }

But when I tried to add the if...else condiction according to the return value

   if(returnData.code === 221){
     Toast.fail("This phone has been registered", 1);
   } else {
     Toast.success("Send verify code successfully", 1);
   }

only to get the error:

Uncaught (in promise) TypeError: Cannot read property 'code' of undefined

I supposed it's the problem about aynchromous and tried to use async await:

  async getVerifyCode() {
    ...
    await this.props.dispatcher.register.send({
        phone: values.phone,
        purpose: 'register',
      })
  }

But get the same error

Cannot read property 'code' of undefined

I wonder why and how to fix this problem ?

added: this is the models

import * as regiserService from '../services/register';

export default {
  namespace: 'register',
  state: {},
  subscriptions: {
  },
  reducers: {
    save(state, { payload: { data: message, code } }) {
      return { ...state, message, code };
    },
  },
  effects: {
    *send({ payload }, { call, put }) {
      const { data } = yield call(regiserService.sendAuthCode, { ...payload });
      const message = data.message;
      yield put({ type: 'save', payload: { data },});
    },
  },
};
1

There are 1 best solutions below

0
On BEST ANSWER

handle conditions in the models solved the problem:

*send({ payload }, { call, put }) {
  const { data } = yield call(regiserService.sendAuthCode, { ...payload });
  if(data.code === 221){
    Toast.fail("This phone has been registered", 1);
  } else {
    Toast.success("Send verify code successfully", 1);
  }
    yield put({ type: 'save', payload: { data }});
  }