0

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?

4
  • Did you decorate your Dashboard using the @connect decorator? Ifaik you need it, to be able to call the dispatch function. See: stackoverflow.com/questions/36553814/… Commented Jul 4, 2017 at 14:29
  • @TomDoodler, yes. It's the last line in the code above. Commented Jul 4, 2017 at 14:30
  • Is state.provider null or undefined before the FETCH_PROVIDER action fires? Commented Jul 4, 2017 at 14:45
  • @MinusFour iit's initial state Commented Jul 4, 2017 at 15:10

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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, }); }); }; } 

5 Comments

I tried and it doesn't work as well. But actually it hasn't to return anything.
Yeah apologies. I assume that redux-thunk is correctly initialised?
Here is initialization: import thunk from 'redux-thunk'; const store = createStore( reducers, applyMiddleware(thunk, routerMiddleware) );
I also tried to change order of middleware but it also didn't help.
Everything looks fine.. that's really strange. If you inspect dispatch right before calling it, can you actually see that it is a function? Is it defined?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.