Extract State Logic to Redux - Step by Step

Tell us what’s happening:

This is the suggested solution but I don’t understand how this work.
Why is state being placed in store and not in the messageReducer?

Your code so far


// define ADD, addMessage(), messageReducer(), and store here:
const ADD = 'ADD'

function addMessage(message) {
  return{
    type:ADD,
    message:message
  }
}
function messageReducer(previousState, action){
   return [...previousState, action.message];
}
let store = {
  state: [],
  getState: () => store.state,
  dispatch: (action) => {
    if (action.type === ADD) {
      store.state = messageReducer(store.state, action);
    }
  }
};

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36.

Link to the challenge:

Redux is very weird - until you get used to it. But don’t be disheartened because this is confusing you - that is normal.

Why is state being placed store and not in the messageReducer?

State is memory. The state is part of the store. That is where you are “storing” the state for the app. Individual React components can still have their own individual state, but keeping an app state in the redux store means that you don’t have to pass it around from component to component.

Why no state in the reducer? Because reducers don’t store data. They are a function they take in and old state and and action and return the new state.

Yes, this is weird. It sure tripped me up for a long time. But just keep doing it and it will start to make sense. In reality, in a “real” app you don’t usually set up your store like that, but in a way this is good because it lets you peak under the covers a bit.

3 Likes

Thank you for the kind response, Kevin. I will read and save it as a reminder of the relationships store/reducer. Happy New Year!

I had this exact same question. The solution to this that FCC provides, like OP is feeling, seems counterintuitive to everything they’ve taught us so far.

Here’s what I came up with (that didn’t pass), which incidentally is EXACTLY how it’s presented on the next challenge!!! :rage:

const ADD = 'ADD';

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

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

const store = Redux.createStore(messageReducer);
1 Like

There is a bit of error in your code. The challenge expects a [] as the default value but you have an empty string ''.

However the example given in the “Get a Hint” is definitely incorrect and not a redux implementation, but a basic imitation of it in JS…

1 Like