Not sure what I am missing... The request is okay and I can see the data when I console.log in the action creator but for some reason the reducer does not work properly.
Here is the code:
Action:
import jsonPlaceholder from "../apis/jsonPlaceholder";
export const fetchPosts = () => {
return async (dispatch) => {
const response = await jsonPlaceholder.get("/posts");
dispatch({ type: "FETCH_POSTS", payload: response.data });
};
};
////
jsonPlaceHolder.js
import axios from "axios";
export default axios.create({
baseURL: "https://jsonplaceholder.typicode.com/",
});
////
Reducers: fetchData.js
const fetchData = (state = [], action) => {
switch (action.type) {
case "FETCH_POSTS":
return action.payloads;
default:
return state;
}
};
export default fetchData;
index.js
import { combineReducers } from "redux";
import fetchData from "./fetchData";
export default combineReducers({
post: fetchData,
});
///
const mapStateToProps = (state) => {
console.log(state);
return { posts: state };
};
export default connect(mapStateToProps, { fetchPosts })(PostList);
The error:
Uncaught (in promise) Error: When called with an action of type "FETCH_POSTS", the slice reducer for key "post" returned undefined. To ignore an action, you must explicitly return the previous state. If you want this reducer to hold no value, you can return null instead of undefined.
const fetchData = (state = [], action) => {
switch (action.type) {
case "FETCH_POSTS":
return action.payload; //fixed
default:
return state;
}
};
export default fetchData;