I am trying to use redux with react to do an api call to GET some data. When calling the function in my component, the reducer is not seeing the action.type and the function is returning a Promise resolved. I've not used redux-thunk before. The code as I have I feel should work but I am having difficulty finding the error. Here is the code.
Index.js
const store = createStore(rootReducer, composeWithDevTools(applyMiddleware(thunkMiddleware, devToolsEnhancer)));
ReactDOM.render(
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>,
document.getElementById('root')
);
Action
import axios from 'axios';
export const GET_ALL_CASES = "GET_ALL_CASES";
const getCasesSuccess = (cases) => {
return {
type: GET_ALL_CASES,
cases
}
};
export const getAllCases = () => {
return (dispatch) => {
axios.get('https://corona.lmao.ninja/countries?sort=country')
.then(response => {
dispatch(getCasesSuccess(response.cases))
})
.catch(error => {
throw(error)
})
}
}
Reducer
import { GET_ALL_CASES } from '../actions';
const initialState = {
allCases: []
}
const rootReducer = (state = initialState, action) => {
switch (action.type) {
case GET_ALL_CASES:
return { ...state, allCases: [...action.cases]}
default:
return state;
}
}
export default rootReducer;
Component
class Second extends React.Component {
constructor(props) {
super(props);
this.state = { }
}
componentDidMount = () => {
getAllCases()
}
render() {
return (
<div>
{this.props.data[0]}
</div>
);
}
}
const mapStateToProps = (state) => (
{
data: state.allCases
}
)
const mapDispatchToProps = dispatch => {
return {
getAllCases: () => dispatch(getAllCases())
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Second);
When calling the function, if I change it to this.props.getAllCases(), I get this error.
Unhandled Rejection (Error): Expected the reducer to be a function.
▶ 5 stack frames were collapsed.
getAllCases
C:/Users/Owner/Desktop/corona-app/src/containers/second.js:33
30 |
31 | const mapDispatchToProps = dispatch => {
32 | return {
> 33 | getAllCases: () => dispatch(getAllCases())
| ^ 34 | }
35 | }
36 |
this.props.getAllCases()
? – Ali TorkiUnhandled Rejection (Error): Expected the reducer to be a function. ▶ 5 stack frames were collapsed. getAllCases C:/Users/Owner/Desktop/corona-app/src/containers/second.js:33 30 | 31 | const mapDispatchToProps = dispatch => { 32 | return { > 33 | getAllCases: () => dispatch(getAllCases()) | ^ 34 | } 35 | } 36 |
– CookieMonsta89const store = createStore(rootReducer, {}, composeWithDevTools(applyMiddleware(thunkMiddleware, devToolsEnhancer)));
– Ali Torki