简体   繁体   中英

redux-thunk dispatch does not work

I have a problem with thunk and async dispatching. So here is my code:

function fetchProvider() {
  return (dispatch) => {
    graphqlService(fetchProviderQuery)
      .then((result) => {
        dispatch({
          type: FETCH_PROVIDER,
          data: result.data.data.CurrentProvider,
        });
      });
  };
}

class Dashboard extends React.Component {
  componentDidMount() {
    this.props.fetchProvider();
  }

  render() {
    const { provider } = this.props;

    return (
      <div>
        <ul>
          <li>id: {provider.id}</li>
          <li>name: {provider.name}</li>
          <li>description: {provider.description}</li>
        </ul>
      </div>
    );
  }
}

const mapStateToProps = (state) => ({
  provider: state.provider,
});

const mapDispatchToProps = (dispatch) => ({
  fetchProvider: () => dispatch(fetchProvider()),
});

export default connect(mapStateToProps, mapDispatchToProps)(Dashboard);

I don't know why but dispatch inside fetchProvider action creator does not work. graphqlService works well and in moment of dispatching FETCH_PROVIDER action data passed to dispatch is correct but then something goes wrong and reducers doesn't called with this action. What possibly could cause this problem?

Finally I found the problem. It was caused by incorrect initialization of react-router-redux middleware. I passed middleware constructor to applyMiddleware instead of constructed middleware.

Your thunk has to return also the promise, or it won't work as expected. Just modify slightly your fetchProvider function

function fetchProvider() {
  return (dispatch) => {
    return graphqlService(fetchProviderQuery)
      .then((result) => {
        dispatch({
          type: FETCH_PROVIDER,
          data: result.data.data.CurrentProvider,
        });
      });
  };
}

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