简体   繁体   中英

How to await the dispatch of the action?

In the redux, i have a (count, remote Count) I set it by default 0 for both!

The main idea is comparing if the count equals the remote count I want to dispatch an action 'true/false' that Locks the App

In home screen get a remote count from API then save it in redux store, it's saved well

but I have an if statement that checks if count == remote count I lock the app

So this statement invokes before I save remote count I guess although I add it in then()

Home screen

  getRemoteCount = async () => {
    try {
      let response = await API.get('/number/subsribtion');
      let remoteCount = response.data.number;
      this.props.saveRemoteCount(remoteCount); // it's saved the remote count! 
    } catch (err) {
      console.log(err);
    }
  };




 componentDidMount() {
    const {remoteCount, count} = this.props;
    this.getRemoteCount().then(() => {
      if (count == remoteCount) {
        console.log('count', count); 
        console.log('remoteCount', remoteCount);//it's log 0!! so the next line invoke!
        this.props.isAppLock(true);
      }
    });
}

Use render to get updated count. componentDidMount run when component mounts for the first time. Save the count on redux store and mapToState in the component.

class C {
  getRemoteCount = async () => {
    try {
      let response = await API.get("/number/subsribtion");
      let remoteCount = response.data.number;
      this.props.saveRemoteCount(remoteCount); // it's saved the remote count!
    } catch (err) {
      console.log(err);
    }
  };
  componentDidMount() {
    this.getRemoteCount();
  }
  render() {
    const { remoteCount, count } = this.props;
    if (count == remoteCount) {
      console.log("count", count);
      console.log("remoteCount", remoteCount); //it's log 0!! so the next line invoke!
      this.props.isAppLock(true);
    }
  }
}

You can use the dispatch async function using redux thunk.

  1. Install redux thunk.

  2. Use as a middleware inside store.

import thunk from 'redux-thunk';
import rootReducer from './reducers';

const store = createStore(rootReducer, applyMiddleware(thunk));
  1. Use it for dispatch async actions.
return async dispatch=>{ let res= await authLogin(data)}

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