After defining the application state and actions, we still need a way to apply actions to change the application state. In Redux, the state is updated through special functions called reducers. Reducers contain the state changing logic of our application.
newState = reducer(state, action)
A reducer function takes the current state object and an action object as arguments. The reducer parses the action object, specifically, the action.type. Depending on the action type, the reducer function either returns a new state, or it simply returns the current state (if the action type is not handled in this reducer).
To write a function, we first have to think of the function signature (the head of the function). A reducer function takes the current state and an action argument. For the state argument, we set a default value, which is what the initial state is going to be.
In our example application, the initial state is an empty array of posts, so we can define the reducer function, as follows:
function postsReducer (state = [], action) {
Now, we will need to parse the action object. The most common way to handle actions in Redux is using a switch statement on action.type. That way, we can have separate cases for all the different action types that the reducer function is going to take care of:
switch (action.type) {
In the switch statement, we handle the CREATE_POST action we defined earlier using Array.concat to add the new post object to the state (an array of posts):
case 'CREATE_POST':
return state.concat([{ user: action.user, text: action.text }])
For all other action types, we simply return the current state:
default:
return state
}
}