Wednesday, 3 May 2017

Redux-Thunk "Actions must be plain objects. Use custom middleware for async actions."

Creating my store with Thunk middleware

import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
const store = createStore(
    reducer, 
    initialState,
    applyMiddleware(thunk)
);

And creating my action which calls a promise

export function getArticle(url) {
  return function (dispatch) {
    fetchArticle(url).then( 
      article => dispatch(setArticle(article)),
    );
  };
}

function fetchArticle(url) {

  return new Promise((resolve, reject) => {

    request
     .get(url)
     .end( (err, res) => {
       if (err || !res.ok) {
         reject('Oh no! error');
       } else {
         resolve(res.body);
       }
     });

  }) 
}

export function setArticle(article){
  return {
    type: constants.SET_ARTICLE,
    article
  }
}

In my article component I am calling dispatch on componentDidMount()

componentDidMount(){
  this.props.dispatch(
    getArticle('http://api.example.com/')
  );
}

But getting error: "Actions must be plain objects. Use custom middleware for async actions.".

What is wrong with this setup? I have tried calling compose(applyMiddleware(thunk)) but to no avail.



via Stretch0

No comments:

Post a Comment