Actions, Reducers, and Store

  • Proof of concept
  • Connect to API

In this section, we create our actions, reducers, and our store. From there, we use our action to make a call to our API and use our reducer to pass that data to our connected components.

The action

The easiest place to start is to create an action. Since we already have the functionality to create and log in users, we will create two actions that we will use to handle our users. We will go over the syntax of the actions below the code.

const Actions = {}
Actions.userNew = function userNew(user) {
return {
type: "USER_NEW",
payload: {
user,
},
}
}
Actions.userLogin = function userLogin(user) {
return {
type: "USER_LOGIN",
payload: {
user,
},
}
}
export default Actions

First we are declaring an Actions object in which we will add all of our actions. This allows us to export a single object that contains all of our actions, so we can later call these actions with something like Actions.userNew after an import statement import Actions from './redux/actions'.

Then we define our first action. Every action must have a type. That is the only required field. The next field passes in our data. It is common to call this something like payload, but you can use whatever term you want. I would avoid using the keyword data because our Phoenix server responds with data, unless you want to end up accessing your data by calling something like data.data.data.user.

Within our payload, we are passing in a user object that we get from the component that dispatched this action (probably a form of some sort). This value gets passed to our reducer which uses it to change the state of our app.

For now, we are just doing a proof of concept, so we aren't going to make an API call to register and log in our user. We will just use our action to set the state of our user in our global Redux store.

You will see in the docs for Redux that people declare their actions as string constants, like the code below.

const USER_LOGIN = "USER_LOGIN"

This is not necessary and we will not be doing this because it's more effort than it's worth at this point in our app. That said, if you're building a huge app, there are perfectly legitimate reasons why you would want to put in this extra work.

If you have a variable called userNew but you called newUser somewhere in your app, it will fail, but it will fail silently. This is because your app will compile properly and run up until you try to dispatch that action, at which point it will cause a run-time error.

If you used a constant, you would get a compile-time error rather than a run-time error because you'd be calling an undeclared variable, so your code wouldn't work unless you used the right variable. This would prevent you from deploying bad code.

The reducer

The reducer is what takes in our actions and turns those into the current state of the app. Reducers should only make calculations and should never have side effects. When you make an API call, you must do this from your action, not your reducer.

We are going to use the native Object.assign to make our immutable data changes, but you can use a library if you prefer. An example would be lodash. What these functions do is make a copy of our state object in order to keep our data immutable. More on this later.

Now we need to create our reducer. The name of the reducer function is the variable name we will use when we want to access the value in the store. We are going to store all user-related values in a valiable called user, so we will name our reducer user.

import { combineReducers } from "redux"
function user(state = {}, action) {
switch (action.type) {
case "USER_NEW":
return state
case "USER_LOGIN":
return Object.assign({}, state, {
email: action.payload.user.email,
})
default:
return state
}
}
const reducers = combineReducers({
user,
})
export default reducers

Our user reducer takes in two values: state and action. state is the previous state of the app before going through the reducer, and action is the action it receives from the action we dispatched.

We are going to use an ES6 feature that allows us to set default values to our parameters. We are setting our default value of state to an empty object ({}), so if user has not been given any values before, we will start it off with an empty object.

Next we write a switch statement that checks the action.type. Recall from the actions we created that each one has a type. If the type matches the action we passed, we tell the reducer what to do. In the example above, the USER_NEW simply passes along state without any changes, while USER_LOGIN assigns the key email to the value that we passed in our action's payload.

It is important to add a default case that passes the state unchanged if there are no other matches. If you do not do this, your app will break if nothing matches, and since we will have multiple reducers, it is inevitable that you will pass actions that don't match one of your reducers.

The combineReducers function allows us to declare all of our reducers in separate functions and combine them before we export.

The store

Now we need to configure our store to take in that reducer. Within redux/store.js, add the following.

import { createStore } from "redux"
import reducers from "./reducers"
const store = createStore(reducers)
export default store

The last thing we need to do to set up Redux is tie our store into our router. Within app/index.js, we need to wrap our entire app in a Provider that passes our store down to each child component. It does this somewhat magically, and all we need to do is import our store and pass it into the Provider component.

...
import { Provider } from "react-redux"
import store from "./redux/store"
...
ReactDOM.render(
<Provider store={store}>
<Router history={hashHistory}>
<Route path="/" component={App}>
<IndexRoute component={Home} />
<Route path="settings" component={Settings} />
</Route>
</Router>
</Provider>,
document.getElementById("root")
)

A note on capitalization: One thing to note is that our Provider is capitalized. Because it is a component that we are using in jsx, if you do not capitalize it, your app will break. Capital letters are more than a convention: they are the rule.

Proof of concept

The last thing we will do is prove that this all works. This is not how we will implement Redux in the final product, but it will show how the pieces all fit together.

Within our Login component, let's connect our store to our component. We do this with the connect function that react-redux gives us. At the top of our component, import connect and at the bottom we have to create a new function, described below the codeblock.

Recall that, for now, to see the Login form, you have to change the formState in our Home component to "login".

import { connect } from "react-redux"
...
const mapStateToProps = state => ({
user: state.user
})
export default connect(mapStateToProps)(cssModules(Login, style))

Recall that with one-line ES2015 arrow functions implicitly return the value after the arrow. So these two are equivalent:

const mapStateToProps = state => {
return {
user: state.user,
}
}
const mapStateToProps = state => ({
user: state.user,
})

The mapStateToProps function takes the state of the app from your store (recall we set the default value of user in our reducer to an empty object {}) and maps that over to the props of your current component. In this case, we are taking state.user from our global store and assigning this.props.user of our current component to that same value. A more accurate name for this might be mapStateOfStoreToPropsOfComponent, but that's perhaps a bit too verbose.

To show that this is working, let's add a console.log within our render function before we return our component.

...
render() {
console.log(this.props.user)
return (
...
)
}

Now, if you change the state of formState in your Home component to "login", you'll see an empty object in your console. This is because we are currently receiving the default, empty object from our reducer.

Object {}

The next step is to dispatch an action with the values from the form that will allow us to change the value of this.props.user.

We do this by importing our Actions and using the dispatch function that we get when we connect our Login component using react-redux.

import Actions from "../../redux/actions"
...
export class Login extends React.Component {
constructor(props) {
super(props)
this.submit = this.submit.bind(this)
}
submit() {
const user = {
email: document.getElementById("signup-email").value,
password: document.getElementById("signup-password").value
}
this.props.dispatch(Actions.userLogin(user))
}
render() {
return (
<div className={style.wrapper}>
<div className={style.form}>
...
<Button
onClick={this.submit}
style={{ width: "100%" }}
type="primary">
Submit
</Button>
</div>
</div>
)
}
}
...

Now go ahead and fill out the login form and submit it. You'll see a new log to your console that has the email address you submitted.

Object {email: "alan@turing.com", password: "badpassword1"}

This worked by taking the values from the inputs, dispatching those values as the userLogin action, which hits our user reducer, which triggers the USER_LOGIN type, which assigns user to { email: action.payload.user.email }.

You may recall that when props are updated, your component automatically updates. In this case, since Login is connected to this.props.user, which was mapped from state.user, our console.log was called again with the updated value.

If that seems like a roundabout way of updating data, you're not alone, but the long-term benefits of keeping your data flow uni-directional far out-weight the upfront cost of setting up some extra code.

Previous: Basics of ReduxNext: Login and Authentication: Part 1