I think you’re not quite getting what this is in front of you – I don’t mean that in a derogatory sense, I think this is quite normal when learning Redux.
First thing is that createStore takes a reducer function, you can only have one. So you need to join postReducer and commentReducer into one big switch statement rather than two. So if you get SET_POSTS going into the switch it sets posts and if you get SET_COMMENTS it sets comments. You can’t just have state as an array, or they’d all get mixed up, so combineReducers joins the switches together but instead of a single array as state, it returns an object with a key for each reducer function:
const rootReducer = combineReducers({
commentReducer: commentReducer,
postReducer: postReducer,
}, []);
Can be thought of as creating this:
function rootReducer(state = { commentReducer: [],
postReducer: [],
}, action) {
switch (action.type) {
case SET_POSTS:
const newPosts = [...state.postReducer, ...action.posts];
return { ...state, postReducer: newPosts };
case SET_COMMENTS:
const newComments = [...state.commentReducer, ...action.comments];
return { ...state, commentReducer: newComments };
default:
return state;
}
}
So the shape of the state is
{
commentReducer: [],
postReducer: [],
}
Hopefully this also shows you that your reducers have very confusing names. Each of them is a function that resolves to a piece of state. Each piece of state is a list of things. One of those is an array of comments, one of those is an array of posts. It is emphasised with redux that reducer function must be pure. What this means is that given an input, the function will always return the same output. And in turn, this means that the function can always be replaced with its return value in the code: the function is the data. postReducer is just a list of posts; it’s not a special thing, it’s just a list of posts.
So commentReducer and postReducer are confusing names, because they aren’t what they are. They are comments and posts. They represent slices of the overall state, which will be an object with some keys.
So rename commentReducer to comments and postReducer to posts.
So now
const rootReducer = combineReducers({ comments, posts })
Which creates state that looks like this:
{
comments: [],
posts: [],
}