Refactoring Redux

  • Separating concerns in Redux
  • Best practices

In this section, we're going to change all of our Redux actions into actions that are more performant, testable, and easier to read. You probably noticed that our Actions were starting to get a little out of control. Now it's time we refactor them.

Incremental refactoring

As far as refactors go, this will be pretty easy so we're going to do this a little differently than previous lessons. Since all of our actions are more or less the same, we're just going to show you how to refactor one of the actions and you should try refactoring the others using the same strategy. If you get stuck, send us a message on Slack and we'll walk you through it.

Let's take a look at our userAuth action:

Actions.userAuth = function userAuth() {
return dispatch =>
fetch(`${process.env.API_HOST}/auth/me`, {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: `Bearer ${localStorage.token}` || "",
},
})
.then(res => {
return res.json()
})
.then(res => {
dispatch({
type: "USER_AUTH",
payload: {
user: res.data,
},
})
})
.catch(err => {
console.warn(err)
})
}

We should also move our actions into new directory and into an index.js file. It will make sense why we are doing this later on.

$ mkdir app/redux/actions
$ touch app/redux/actions/{index,async}.js

Then copy over the existing content from actions.js into async.js and delete actions.js. So now your Redux directory/file structure should look like this, with all of your actions living in async.js:

redux
|-- reducers.js
|-- store.js
|-- actions
|-- async.js
|-- index.js

The next thing we should do is change our exports so that we're exporting each action individually. So let's get rid of the Actions object and simply use export function. We'll also need to get rid of that default export at the end. So now, each of your functions should look like this (with the body of the actions removed for brevity):

export function userAuth() {
...
}
export function userNew(user) {
...
}
export function userLogin(user) {
...
}
export function organizationNew(organization) {
...
}

But now we aren't exporting our actions, so nothing will work. In order to export all of our exported actions, let's add an export in our index.js file that takes in all the actions from async.js.

export * from "./async"

And now we're ready for major refactoring.

Remove Try-Catch

The first thing we should do is remove the catch statement at the end and handle errors within then. This is debatable, but using try-catch for logic can end up displaying errors that aren't what you would expect. For example, if you had a spelling error or something like that within your then, it would raise in your catch statement, making bugs harder to track down. Check out this comment from Dan Abramov for another example.

Actions.userAuth = function userAuth() {
return dispatch =>
fetch(`${process.env.API_HOST}/auth/me`, {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: `Bearer ${localStorage.token}` || "",
},
})
.then(res => {
return res.json()
})
.then(res => {
dispatch({
type: "USER_AUTH",
payload: {
user: res.data,
},
})
})
}

Pulling out HTTP calls

The next part of our refactor involves pulling our HTTP calls into a separate file. Let's create an http.js file within our actions directory and add some logic there.

$ touch app/redux/actions/http.js

Again, we're only going to change userAuth in this lesson, but you should refactor the other actions as well.

export function userAuth() {
return fetch(`${process.env.API_HOST}/auth/me`, {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: `Bearer ${localStorage.token}` || "",
},
})
}

So now that we have our HTTP call pulled out, we can use it in our async.js file.

import * as http from "./http"
export function userAuth() {
return dispatch => {
http
.userAuth()
.then(res => {
return res.json()
})
.then(res => {
dispatch({
type: "USER_AUTH",
payload: {
user: res.data,
},
})
})
}
}

This will allow us to write tests specific to our HTTP calls and different tests specific to our asynchronous actions.

Async-Await

The next thing to do is to get rid of the then block by using the ES2016 Async-Await which was added in July of 2016. If you're not familiar, it's similar to a generator.

We're also going to add a failure action (USER_AUTH_FAILURE) in case we want to do something in the event of auth failure.

import * as http from "./http"
export function userAuth() {
return async dispatch => {
const response = await http.userAuth()
if (response.status !== 200) {
dispatch({ type: "USER_AUTH_FAILURE" })
} else {
const result = await response.json()
dispatch({
type: "USER_AUTH",
payload: {
user: result.data,
},
})
}
}
}

If you try to run this, you will get an error. That's because we need babel-polyfill to handle async-await until it's widely supported.

$ npm install --save-dev babel-polyfill

Then add it as an entry point in our webpack configuration just like we did with whatwg-fetch. You'll have to do this in both webpack.config.js and webpack.prod.config.js.

...
module.exports = {
devtool: 'eval',
entry: [
'whatwg-fetch',
'babel-polyfill',
'webpack-dev-server/client?http://localhost:3000',
'./app/index'
],
...
}

Although it doesn't affect us here, something to keep in mind that is that every time you dispatch and change state, you're causing a re-render. So if you look at our userNew function, you'll see that we're dispatching the user data to our reducer, then calling userAuth. This will cause two renders, which you may or may not want to do depending on your situation.

Separating synchronous actions

The last major change we'll make is to pull out our synchronous actions. These are all of our actions that don't require a request to our server. So that includes changing modal states, loading states, and dispatching the results of an asynchronous request.

$ touch app/redux/actions/sync.js
export const userAuthSuccess = user => ({
type: "USER_AUTH",
payload: {
user,
},
})
export const userAuthFailure = () => ({
type: "USER_AUTH_FAILURE",
})
import * as http from "./http"
import * as sync from "./sync"
export function userAuth() {
return async dispatch => {
const response = await http.userAuth()
if (response.status !== 200) {
dispatch(sync.userAuthFailure())
} else {
const result = await response.json()
dispatch(sync.userAuthSuccess(result.data))
}
}
}

We're also going to want to use our synchronous actions in some of our components, so we should add an export in our index.js file that gives us access to them.

export * from "./sync"
export * from "./async"

The only other immediate change you should make for this refactor is in you App component. Instead of importing Actions, we need to import the individual action, userAuth. And then we have to change the dispatch.

import { userAuth } from "../../redux/actions"
export class App extends React.Component {
componentDidMount() {
this.props.dispatch(userAuth())
}
...
}

And that should do it. Our Redux actions are now split into functions that are task-specific, which will make them much easier to test and reason about. When you refresh, your app should still function.

You will need to refactor out all of the Actions imports, since we are only exporting named exports now. So, for example, the Login component should now import userLogin like this:

// Old import
import Actions from "../../redux/actions"
// New import
import { userLogin } from "../../redux/actions"
Previous: SSL and CloudFrontNext: Basics of Analytics