{"componentChunkName":"component---src-templates-lesson-js","path":"/phoenix-chat/refactoring-redux","result":{"data":{"mdx":{"body":"function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\n\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\n\n/* @jsx mdx */\nvar _frontmatter = {\n  \"title\": \"Refactoring Redux\",\n  \"order\": 54,\n  \"free\": false,\n  \"active\": true,\n  \"tech\": [\"react\", \"redux\"]\n};\n\nvar makeShortcode = function makeShortcode(name) {\n  return function MDXDefaultShortcode(props) {\n    console.warn(\"Component \" + name + \" was not imported, exported, or provided by MDXProvider as global scope\");\n    return mdx(\"div\", props);\n  };\n};\n\nvar layoutProps = {\n  _frontmatter: _frontmatter\n};\nvar MDXLayout = \"wrapper\";\nreturn function MDXContent(_ref) {\n  var components = _ref.components,\n      props = _objectWithoutProperties(_ref, [\"components\"]);\n\n  return mdx(MDXLayout, _extends({}, layoutProps, props, {\n    components: components,\n    mdxType: \"MDXLayout\"\n  }), mdx(\"h1\", null, \"Refactoring Redux\"), mdx(\"ul\", null, mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Separating concerns in Redux\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Best practices\")), mdx(\"p\", null, \"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.\"), mdx(\"h2\", null, \"Incremental refactoring\"), mdx(\"p\", null, \"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.\"), mdx(\"p\", null, \"Let's take a look at our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"userAuth\"), \" action:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"Actions.userAuth = function userAuth() {\\n  return dispatch =>\\n    fetch(`${process.env.API_HOST}/auth/me`, {\\n      method: \\\"GET\\\",\\n      headers: {\\n        Accept: \\\"application/json\\\",\\n        \\\"Content-Type\\\": \\\"application/json\\\",\\n        Authorization: `Bearer ${localStorage.token}` || \\\"\\\",\\n      },\\n    })\\n      .then(res => {\\n        return res.json()\\n      })\\n      .then(res => {\\n        dispatch({\\n          type: \\\"USER_AUTH\\\",\\n          payload: {\\n            user: res.data,\\n          },\\n        })\\n      })\\n      .catch(err => {\\n        console.warn(err)\\n      })\\n}\\n\")), mdx(\"p\", null, \"We should also move our actions into new directory and into an \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"index.js\"), \" file. It will make sense why we are doing this later on.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ mkdir app/redux/actions\\n$ touch app/redux/actions/{index,async}.js\\n\")), mdx(\"p\", null, \"Then copy over the existing content from \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"actions.js\"), \" into \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"async.js\"), \" and delete \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"actions.js\"), \". So now your Redux directory/file structure should look like this, with all of your actions living in \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"async.js\"), \":\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"redux\\n|-- reducers.js\\n|-- store.js\\n|-- actions\\n    |-- async.js\\n    |-- index.js\\n\")), mdx(\"p\", null, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Actions\"), \" object and simply use \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"export function\"), \". We'll also need to get rid of that \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"default export\"), \" at the end. So now, each of your functions should look like this (with the body of the actions removed for brevity):\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"export function userAuth() {\\n  ...\\n}\\n\\nexport function userNew(user) {\\n  ...\\n}\\n\\nexport function userLogin(user) {\\n  ...\\n}\\n\\nexport function organizationNew(organization) {\\n  ...\\n}\\n\")), mdx(\"p\", null, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"export\"), \" in our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"index.js\"), \" file that takes in all the actions from \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"async.js\"), \".\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"export * from \\\"./async\\\"\\n\")), mdx(\"p\", null, \"And now we're ready for major refactoring.\"), mdx(\"h2\", null, \"Remove Try-Catch\"), mdx(\"p\", null, \"The first thing we should do is remove the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"catch\"), \" statement at the end and handle errors within \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"then\"), \". This is debatable, but using \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"then\"), \", it would raise in your \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"catch\"), \" statement, making bugs harder to track down. Check out \", mdx(\"a\", {\n    \"href\": \"https://github.com/facebook/react/issues/7617#issuecomment-247710003\",\n    \"parentName\": \"p\"\n  }, \"this comment\"), \" from Dan Abramov for another example.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"Actions.userAuth = function userAuth() {\\n  return dispatch =>\\n    fetch(`${process.env.API_HOST}/auth/me`, {\\n      method: \\\"GET\\\",\\n      headers: {\\n        Accept: \\\"application/json\\\",\\n        \\\"Content-Type\\\": \\\"application/json\\\",\\n        Authorization: `Bearer ${localStorage.token}` || \\\"\\\",\\n      },\\n    })\\n      .then(res => {\\n        return res.json()\\n      })\\n      .then(res => {\\n        dispatch({\\n          type: \\\"USER_AUTH\\\",\\n          payload: {\\n            user: res.data,\\n          },\\n        })\\n      })\\n}\\n\")), mdx(\"h2\", null, \"Pulling out HTTP calls\"), mdx(\"p\", null, \"The next part of our refactor involves pulling our HTTP calls into a separate file. Let's create an \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"http.js\"), \" file within our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"actions\"), \" directory and add some logic there.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ touch app/redux/actions/http.js\\n\")), mdx(\"p\", null, \"Again, we're only going to change \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"userAuth\"), \" in this lesson, but you should refactor the other actions as well.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"export function userAuth() {\\n  return fetch(`${process.env.API_HOST}/auth/me`, {\\n    method: \\\"GET\\\",\\n    headers: {\\n      Accept: \\\"application/json\\\",\\n      \\\"Content-Type\\\": \\\"application/json\\\",\\n      Authorization: `Bearer ${localStorage.token}` || \\\"\\\",\\n    },\\n  })\\n}\\n\")), mdx(\"p\", null, \"So now that we have our HTTP call pulled out, we can use it in our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"async.js\"), \" file.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"import * as http from \\\"./http\\\"\\n\\nexport function userAuth() {\\n  return dispatch => {\\n    http\\n      .userAuth()\\n      .then(res => {\\n        return res.json()\\n      })\\n      .then(res => {\\n        dispatch({\\n          type: \\\"USER_AUTH\\\",\\n          payload: {\\n            user: res.data,\\n          },\\n        })\\n      })\\n  }\\n}\\n\")), mdx(\"p\", null, \"This will allow us to write tests specific to our HTTP calls and different tests specific to our asynchronous actions.\"), mdx(\"h2\", null, \"Async-Await\"), mdx(\"p\", null, \"The next thing to do is to get rid of the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"then\"), \" block by using the ES2016 \", mdx(\"a\", {\n    \"href\": \"https://github.com/tc39/ecmascript-asyncawait\",\n    \"parentName\": \"p\"\n  }, \"Async-Await\"), \" which was added in July of 2016. If you're not familiar, it's similar to a generator.\"), mdx(\"p\", null, \"We're also going to add a failure action (\", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"USER_AUTH_FAILURE\"), \") in case we want to do something in the event of auth failure.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"import * as http from \\\"./http\\\"\\n\\nexport function userAuth() {\\n  return async dispatch => {\\n    const response = await http.userAuth()\\n    if (response.status !== 200) {\\n      dispatch({ type: \\\"USER_AUTH_FAILURE\\\" })\\n    } else {\\n      const result = await response.json()\\n      dispatch({\\n        type: \\\"USER_AUTH\\\",\\n        payload: {\\n          user: result.data,\\n        },\\n      })\\n    }\\n  }\\n}\\n\")), mdx(\"p\", null, \"If you try to run this, you will get an error. That's because we need \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"babel-polyfill\"), \" to handle \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"async-await\"), \" until it's widely supported.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ npm install --save-dev babel-polyfill\\n\")), mdx(\"p\", null, \"Then add it as an entry point in our webpack configuration just like we did with \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"whatwg-fetch\"), \". You'll have to do this in both \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"webpack.config.js\"), \" and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"webpack.prod.config.js\"), \".\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"...\\nmodule.exports = {\\n  devtool: 'eval',\\n  entry: [\\n    'whatwg-fetch',\\n    'babel-polyfill',\\n    'webpack-dev-server/client?http://localhost:3000',\\n    './app/index'\\n  ],\\n  ...\\n}\\n\")), mdx(\"p\", null, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"userNew\"), \" function, you'll see that we're dispatching the user data to our reducer, then calling \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"userAuth\"), \". This will cause two renders, which you may or may not want to do depending on your situation.\"), mdx(\"h2\", null, \"Separating synchronous actions\"), mdx(\"p\", null, \"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.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ touch app/redux/actions/sync.js\\n\")), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"export const userAuthSuccess = user => ({\\n  type: \\\"USER_AUTH\\\",\\n  payload: {\\n    user,\\n  },\\n})\\n\\nexport const userAuthFailure = () => ({\\n  type: \\\"USER_AUTH_FAILURE\\\",\\n})\\n\")), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"import * as http from \\\"./http\\\"\\nimport * as sync from \\\"./sync\\\"\\n\\nexport function userAuth() {\\n  return async dispatch => {\\n    const response = await http.userAuth()\\n    if (response.status !== 200) {\\n      dispatch(sync.userAuthFailure())\\n    } else {\\n      const result = await response.json()\\n      dispatch(sync.userAuthSuccess(result.data))\\n    }\\n  }\\n}\\n\")), mdx(\"p\", null, \"We're also going to want to use our synchronous actions in some of our components, so we should add an export in our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"index.js\"), \" file that gives us access to them.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"export * from \\\"./sync\\\"\\nexport * from \\\"./async\\\"\\n\")), mdx(\"p\", null, \"The only other immediate change you should make for this refactor is in you \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"App\"), \" component. Instead of importing \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Actions\"), \", we need to import the individual action, \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"userAuth\"), \". And then we have to change the dispatch.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"import { userAuth } from \\\"../../redux/actions\\\"\\n\\nexport class App extends React.Component {\\n  componentDidMount() {\\n    this.props.dispatch(userAuth())\\n  }\\n\\n  ...\\n}\\n\")), mdx(\"p\", null, \"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.\"), mdx(\"p\", null, \"You will need to refactor out all of the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Actions\"), \" imports, since we are only exporting named exports now. So, for example, the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Login\"), \" component should now import \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"userLogin\"), \" like this:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"// Old import\\nimport Actions from \\\"../../redux/actions\\\"\\n\\n// New import\\nimport { userLogin } from \\\"../../redux/actions\\\"\\n\")));\n}\n;\nMDXContent.isMDXComponent = true;","excerpt":"Refactoring Redux Separating concerns in Redux Best practices In this section, we're going to change all of our Redux actions into actions…","frontmatter":{"title":"Refactoring Redux","order":54,"active":true,"free":false,"tech":["react","redux"]}}},"pageContext":{"slug":"refactoring-redux","prevNode":{"frontmatter":{"title":"SSL and CloudFront","active":true,"free":false,"order":53,"tech":["cloudfront"]},"fields":{"slug":"ssl-and-cloudfront"}},"nextNode":{"frontmatter":{"title":"Basics of Analytics","active":true,"free":false,"order":55,"tech":null},"fields":{"slug":"basics-of-analytics"}}}},"staticQueryHashes":["1723017916"]}