Tell us what’s happening:
I have ran the tests and the check for “The store should exist and have an initial state set to an empty array.” and “Dispatching addMessage against the store should immutably add a new message to the array of messages held in state.” return false. I am unable to find the issue with my code. Any help will be greatly appreciated. Thanks!
**Your code so far**
// Define ADD, addMessage(), messageReducer(), and store here:
const ADD="ADD";
const addMessage=message=>{return {type:ADD,message};};
const messageReducer=(previousState=[],action)=>{
switch(action.type){
case ADD:return [...previousState,action.message];break;
default:return previousState;
}
};
const store=Redux.createStore(messageReducer);
console.log(store.getState());
store.dispatch(addMessage("Rest"));
console.log(store.getState());
store.dispatch(addMessage("big words here"));
console.log(store.getState());
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.84 Safari/537.36
When I get rid of the last 5 lines of test code, it passes for me. They are messing with the state and throwing off the test, I guess.
On another note… Please don’t try to cram so much code onto one line. Whitespace and spreading things out make them more readable. There is now advantage to cramming everything into as small a space as possible. And use indenting. And spaces. Take your code to a code formatting or prettier site and see what it says. If you code like that, the people at work are going to start slashing your tires in the parking lot.
Also,
case ADD:return [...previousState,action.message];break;
Once you return in a case, the break is unnecessary. There is no situation where that would get run - it’s already executed the function.
I would also suggest that it is “state”, not “previousState”. It is the current state. I think the latter is used sometimes when we have a new incoming state and you need to distinguish.
Learn the rules and learn why before you start breaking them.
Oh yeah, that solved it. I’m guessing it was since it had modified the state and the tests were running on the modified state. Thanks!
Yeah, I usually don’t write crammed code for work. I was trying to figure out the issue after rewriting this code multiple times so I decided to cram it and forgot to format it into a more readable state. Sorry about that.
Originally, my code didn’t have the break and I had named the previousState argument as state. But as it was giving errors, I decided to change the wordings and format it close to the solution provided by the camperbot. But yeah, you are right. I’m certain it is used when there is a need to distinguish.