So right now I’m doing one of the React-Redux challenges (Extract State Logic to Redux) and I have two answers that differ in a piece of code in the reducer function. They seem to me like they should be doing the same thing but one of them is correct and one isn’t.
Incorrect reducer:
const messageReducer = (state = [], action) => {
switch(action.type){
case ADD:
let nS = [...state]
return nS.push(action.message);
default:
return state;
}
};
Correct reducer:
const messageReducer = (state = [], action) => {
switch(action.type){
case ADD:
return [...state, action.message]
default:
return state;
}
};
Now I know that with Redux you generally want to use the latter method, but I don’t really understand why the first one fails the tests. Shouldn’t both ADD cases return the same thing without mutating the original state?
I know about shallow vs deep copies, but since state is just an empty array and it there’s nothing going on with nested objects or anything like that I don’t really get why both ways don’t work.
EDIT: Whoops, nevermind I forgot push just mutates the array and doesn’t return the result. Got it.