React and Redux: Extract State Logic to Redux

React and Redux: Extract State Logic to Redux
0

#1

I am working on the React and Redux challenges. On the third challenge ‘extract state logic to redux’ I am stuck. I realize it is just basic redux but I am not able to solve it. My code is as follows:

// define ADD, addMessage(), messageReducer(), and store here:
const ADD = 'ADD';
const defaultState = {
  messages: []
};

function addMessage(msg) {
  return {
    type: ADD,
    message: msg
  };
};

const messageReducer = (state = defaultState, action) => {
  switch (action.type) {
    case ADD:
      var newState = {
        messages: state.messages.concat(action.message)
      };
      console.log(newState);
      return newState;
      break;
    default:
      return state
  };
  
};

const store = Redux.createStore(messageReducer);

I am failing on the ‘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.’ tests. I added a lot of console logs not shown here and I can clearly see that when the tests are run the state object is updated with the new message in the messages array. Any hints will be showered with thank yous.


#2

Hi biko-the-bird,

The 1st challenge is: “The initial state should equal an empty array”. In your code the initial state is set to an object and both methods return objects.

I’m guessing you’re failing test 4 and 6. Can you confirm this?


#3

Hi pwkrz,
I was failing tests 4 and 5. 6 passes. You were correct though my issue was solved by returning an array instead of a object. Thank you very much for responding so promptly


#4

You state in Reducer should be set to defaultState.messages so your state is empty array. And in case of ADD write return […state, action.message]. I hope this will help you.