Reputation: 1
In the componentDidMount() method, i dispatched an async action that fetch some data from another API. In the redux dev tool, the fetch data success method is dispatched, and it has the right payload retrieved from response. However, this action did not seem to reach the reducer, as the state in my redux store was unchanged. I injected console.log() in my reducer and noticed that the reducer was not reached.
I viewed other relevant posts but i cant find any solutions.
I have provided the relevant code snippets and will appreciate any help! i am using thunk as the middleware.
//index.js
const rootReducer = combineReducers({
search: searchBarReducer,
});
const composeEnhancers = process.env.NODE_ENV === 'development' ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : null || compose;
const store = createStore(rootReducer, composeEnhancers(applyMiddleware(thunk)));
const app = (
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
);
ReactDOM.render(app, document.getElementById("root"));
registerServiceWorker();
//action creator
export const suggestionsInit = (filter) => {
console.log("[suggestionsInit]")
return (dispatch) => {
let result = [];
axios
.get("")
.then((response) => {
response.data.forEach((element) => {
result.push(element.moduleCode);
});
dispatch(fetchSuggestionsSuccess(result));
})
//
};
};
export const fetchSuggestionsSuccess = (data) => {
return {
type: actionTypes.FETCH_SUGGESTIONS_SUCCESS,
data: data,
};
};
//reducer
const initialState = {
modules: [],
//
}
const reducer = (state = initialState, action) => {
switch (action.type) {
case actionTypes.SEARCHBAR_INT:
return {
...state,
modules: action.data
}
default: return state;
}
}
//associated component
componentDidMount() {
console.log("[componentDidMount]");
this.props.dispatchSuggestionsInit("modules");
}
...
//after class body
const mapStateToProps = (state) => {
return {
modules: state.search.modules,
};
};
const mapDispatchToProps = (dispatch) => {
return {
dispatchSuggestionsInit: (filter) => dispatch(actions.suggestionsInit(filter)),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(withErrorHandler(SearchBar, axios));
//with error handler is just another higher order component and it does not affect the functionality.
Upvotes: 0
Views: 415
Reputation: 3464
In you reducer file you should be listening/checking for the success case of dispatch, reason being you when you dispatch the success data the action you are dispatching with action type of actionTypes.FETCH_SUGGESTIONS_SUCCESS
and not INIT one.
const reducer = (state = initialState, action) => {
switch (action.type) {
case actionTypes.FETCH_SUGGESTIONS_SUCCESS:
return {
...state,
modules: action.data
};
default: return state;
}
};
Upvotes: 0