Extract State Logic to Redux - addMessage

Extract State Logic to Redux - addMessage
0

#1

Tell us what’s happening:

The one thing I cannot seem to wrap my head around is where the function addMessage is being called. At what point does messageReducer get the addMessage function for an action?

Your code so far


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

const ADD = 'ADD';
const defaultState = {
    messages: []
}

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

const messageReducer = (state = defaultState.messages,action) => {
if(action.type == ADD){
    let newState = state.concat(action.message);
    return newState;
}
else{
    return state;
}
}

const store = Redux.createStore(messageReducer)

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0.

Link to the challenge:
https://learn.freecodecamp.org/front-end-libraries/react-and-redux/extract-state-logic-to-redux


#2

addMessage will be called by some component down the tree, like this:

<SomeComponent onClick={props.addMessage} />

Normally, you wouldn’t have the action creators like addMessage defined in the same file. It should all make more sense once you put this together into a real app.


#3

You will pass the add message action into what is called a dispatch function.

dispatch(addMessage('mymessage');

This creates an action in your store. The store actually passes this action to every reducer. Every reducer then check’s if they need to change the state:

if(action.type == ADD)

You don’t ever call a reducer directly. You just dispatch actions which your reducers listen in to. The reducer then changes the state. Your components will then get this new state.

As @PortableStick said, it will all make more sense when you include redux in components.