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.
npm install redux-thunk
. console.logthunk
to make sure that exists. Your code looks fine, it just seems like thunk is not registering. – Eric Kambestad