Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

reactjs - how to async/await redux-thunk actions?

action.js

export function getLoginStatus() {
  return async(dispatch) => {
    let token = await getOAuthToken();
    let success = await verifyToken(token);
    if (success == true) {
      dispatch(loginStatus(success));
    } else {
      console.log("Success: False");
      console.log("Token mismatch");
    }
    return success;
  }
}

component.js

  componentDidMount() {
    this.props.dispatch(splashAction.getLoginStatus())
      .then((success) => {
        if (success == true) {
          Actions.counter()
        } else {
          console.log("Login not successfull");
        }
     });
   }

However, when I write component.js code with async/await like below I get this error:

Possible Unhandled Promise Rejection (id: 0): undefined is not a function (evaluating 'this.props.dispatch(splashAction.getLoginStatus())')

component.js

  async componentDidMount() {
     let success = await this.props.dispatch(splashAction.getLoginStatus());
     if (success == true) {
       Actions.counter()
     } else {
       console.log("Login not successfull");
     }
   }

How do I await a getLoginStatus() and then execute the rest of the statements? Everything works quite well when using .then(). I doubt something is missing in my async/await implementation. trying to figure that out.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The Promise approach

export default function createUser(params) {
  const request = axios.post('http://www...', params);

  return (dispatch) => {
    function onSuccess(success) {
      dispatch({ type: CREATE_USER, payload: success });
      return success;
    }
    function onError(error) {
      dispatch({ type: ERROR_GENERATED, error });
      return error;
    }
    request.then(success => onSuccess, error => onError);
  };
}

The async/await approach

export default function createUser(params) {  
  return async dispatch => {
    function onSuccess(success) {
      dispatch({ type: CREATE_USER, payload: success });
      return success;
    }
    function onError(error) {
      dispatch({ type: ERROR_GENERATED, error });
      return error;
    }
    try {
      const success = await axios.post('http://www...', params);
      return onSuccess(success);
    } catch (error) {
      return onError(error);
    }
  }
}

Referenced from the Medium post explaining Redux with async/await: https://medium.com/@kkomaz/react-to-async-await-553c43f243e2


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...