Extract State Logic to Redux (what am I missing)

Tell us what’s happening:
Describe your issue in detail here.

  **Your code so far**

// Define ADD, addMessage(), messageReducer(), and store here:

const ADD = 'ADD'

const addMessage = (mssg) => { 
return(
  {type: ADD, message: mssg}
)
}

function messageReducer(state = [], action){
switch(action.type){
  case 'ADD':
    return state.concat([action.message]);
  default:
    return state;
}
}

const store = Redux.createStore(messageReducer);

console.log(store.getState())
store.dispatch(addMessage('das'))
console.log(store.getState())
store.dispatch(addMessage('adsada'))
console.log(store.getState())

/****************************/

So I am getting two errors:

  1. The store doesn’t have an initial state set to an empty array.
  2. Dispatching addMessage against the store is not immutably adding a new message to the array of messages held in state but I swear it is adding those messages.

You didn’t do the final step in the instructions:

Finally, create your Redux store and pass it the reducer.

You were taught how to do that in this lesson.

When I add that in, your code passes for me.

Oops, scratch that. I didn’t copy all of your code. You were doing that just fine.

No, the problem is the lines at the bottom of your code. Presumably the tests are expecting a store in a virgin state but your debug code is initializing and running your reducer before the test even starts, causing it to get into a bad state, I think.

When I remove the bottom 5 lines from your code, it passes for me.

Does ADD in the addMessage function need to be in quotations? So instead of {type: ADD, message: mssg}, it should be {type: ‘ADD’, message: mssg}

Thx for the input, I eventually did figure that out as well. Guess i do need to be more conscious of the debug code.

@SamV

What you are suggesting would work but is not necessary because of this line:

const ADD = 'ADD'

so the variable ADD already means that. This is a common pattern in React, to define your types. I know it looks odd but it becomes useful when your redux store gets big and these are all split into different files.

That constant should have also been used in the reducer:

  case ADD:

@TTime

Yeah, it happens. Usually it is not an issue but in this case, the test needs a fresh state. The nature of state is that it is changing and being stored over time.

True, I did do the case ADD: earlier but I changed it up cause I was trying to figure out why the code wasnt running.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.