Reputation: 111
I am really new to Redux and its concepts, especially middleware so I do apologise for any stupid errors.
In this project of mine, I need to use redux-thunk. I've looked at a few guides and explanations on how to apply them. I then kept receiving an error "Uncaught TypeError: Cannot read property 'dispatch' of undefined". I opened developer tools and got shown this error:
I have no idea if I am doing anything right. Below are the codes for my action creators and store.
actions/index.js
import axios from 'axios';
export function fetchLessons() {
console.log('called!');
return function(dispatch) {
axios.get(`${ROOT_URL}/lessons`)
.then((response) => {
dispatch(fetchLessonsSuccess(response))
})
.catch((err) => {
dispatch(fetchLessonsError(err))
})
}
}
function fetchLessonsError(){
return "An error has occured";
}
function fetchLessonsSuccess(response) {
return {
type: FETCH_LESSONS,
payload: request
};
}
index.js(store)
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware, compose } from 'redux';
import { Router, browserHistory } from 'react-router';
import rootReducer from './reducers/index';
import routes from './routes';
import promise from 'redux-promise';
import thunk from 'redux-thunk';
const middleware = applyMiddleware(promise(), thunk);
const store = createStore(rootReducer, compose(middleware));
ReactDOM.render(
<Provider store={store}>
<Router history={browserHistory} routes={routes} />
</Provider>
, document.querySelector('.container'));
Upvotes: 2
Views: 1433
Reputation: 471
i am not totally sure but something like this
export function fetchLessons() {
console.log('called!');
return function(dispatch) {
return dispatch({
type: 'FETCH_LESSONS',
payload: axios.get(`${ROOT_URL}/lessons`)
.then((response) => {
dispatch(fetchLessonsSuccess(response))
})
.catch((err) => {
dispatch(fetchLessonsError(err))
});
});
};
}
function fetchLessonsError(){
return "An error has occured";
}
function fetchLessonsSuccess(response) {
return {
type: 'FETCH_LESSONS_FULFILLED',
payload: response
};
}
Upvotes: 0
Reputation: 67459
I believe your call to applyMiddleware()
is slightly off. You want to pass the imported promise middleware directly, not call it: applyMiddleware(promise, thunk)
.
That function is basically a factory. Redux will call it and pass in the store's dispatch
function, which the middleware can then use to dispatch actions whenever it's ready.
Upvotes: 4