{"componentChunkName":"component---src-templates-lesson-js","path":"/phoenix-chat/actions-reducers-and-store","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\": \"Actions, Reducers, and Store\",\n  \"order\": 18,\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, \"Actions, Reducers, and Store\"), mdx(\"ul\", null, mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Proof of concept\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Connect to API\")), mdx(\"p\", null, \"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.\"), mdx(\"h2\", null, \"The \", mdx(\"inlineCode\", {\n    \"parentName\": \"h2\"\n  }, \"action\")), mdx(\"p\", null, \"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.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"const Actions = {}\\n\\nActions.userNew = function userNew(user) {\\n  return {\\n    type: \\\"USER_NEW\\\",\\n    payload: {\\n      user,\\n    },\\n  }\\n}\\n\\nActions.userLogin = function userLogin(user) {\\n  return {\\n    type: \\\"USER_LOGIN\\\",\\n    payload: {\\n      user,\\n    },\\n  }\\n}\\n\\nexport default Actions\\n\")), mdx(\"p\", null, \"First we are declaring an \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Actions.userNew\"), \" after an import statement \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"import Actions from './redux/actions'\"), \".\"), mdx(\"p\", null, \"Then we define our first action. Every action must have a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"type\"), \". That is the only required field. The next field passes in our data. It is common to call this something like \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"payload\"), \", but you can use whatever term you want. I would avoid using the keyword \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"data\"), \" because our Phoenix server responds with \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"data\"), \", unless you want to end up accessing your data by calling something like \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"data.data.data.user\"), \".\"), mdx(\"p\", null, \"Within our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"payload\"), \", we are passing in a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user\"), \" object that we get from the component that dispatched this action (probably a form of some sort). This value gets passed to our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"reducer\"), \" which uses it to change the state of our app.\"), mdx(\"p\", null, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"store\"), \".\"), mdx(\"p\", null, \"You will see in the docs for Redux that people declare their actions as string constants, like the code below.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"const USER_LOGIN = \\\"USER_LOGIN\\\"\\n\")), mdx(\"p\", null, \"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.\"), mdx(\"p\", null, \"If you have a variable called \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"userNew\"), \" but you called \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"newUser\"), \" somewhere in your app, it will fail, but it will fail silently. This is because your app will compile properly and run \", mdx(\"em\", {\n    \"parentName\": \"p\"\n  }, \"up until\"), \" you try to dispatch that action, at which point it will cause a run-time error.\"), mdx(\"p\", null, \"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.\"), mdx(\"h2\", null, \"The \", mdx(\"inlineCode\", {\n    \"parentName\": \"h2\"\n  }, \"reducer\")), mdx(\"p\", null, \"The reducer is what takes in our actions and turns those into the current state of the app. \", mdx(\"strong\", {\n    \"parentName\": \"p\"\n  }, \"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.\"), mdx(\"p\", null, \"We are going to use the native \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Object.assign\"), \" to make our immutable data changes, but you can use a library if you prefer. An example would be \", mdx(\"a\", {\n    \"href\": \"https://lodash.com/docs\",\n    \"parentName\": \"p\"\n  }, \"lodash\"), \". What these functions do is make a copy of our state object in order to keep our data immutable. More on this later.\"), mdx(\"p\", null, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user\"), \", so we will name our reducer \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user\"), \".\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"import { combineReducers } from \\\"redux\\\"\\n\\nfunction user(state = {}, action) {\\n  switch (action.type) {\\n    case \\\"USER_NEW\\\":\\n      return state\\n    case \\\"USER_LOGIN\\\":\\n      return Object.assign({}, state, {\\n        email: action.payload.user.email,\\n      })\\n    default:\\n      return state\\n  }\\n}\\n\\nconst reducers = combineReducers({\\n  user,\\n})\\n\\nexport default reducers\\n\")), mdx(\"p\", null, \"Our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user\"), \" reducer takes in two values: \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"state\"), \" and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"action\"), \". \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"state\"), \" is the previous state of the app before going through the reducer, and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"action\"), \" is the action it receives from the action we dispatched.\"), mdx(\"p\", null, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"state\"), \" to an empty object (\", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"{}\"), \"), so if \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user\"), \" has not been given any values before, we will start it off with an empty object.\"), mdx(\"p\", null, \"Next we write a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"switch\"), \" statement that checks the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"action.type\"), \". Recall from the actions we created that each one has a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"type\"), \". If the type matches the action we passed, we tell the reducer what to do. In the example above, the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"USER_NEW\"), \" simply passes along state without any changes, while \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"USER_LOGIN\"), \" assigns the key \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"email\"), \" to the value that we passed in our action's \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"payload\"), \".\"), mdx(\"p\", null, \"It is important to add a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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.\"), mdx(\"p\", null, \"The \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"combineReducers\"), \" function allows us to declare all of our reducers in separate functions and combine them before we export.\"), mdx(\"h2\", null, \"The \", mdx(\"inlineCode\", {\n    \"parentName\": \"h2\"\n  }, \"store\")), mdx(\"p\", null, \"Now we need to configure our store to take in that reducer. Within \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"redux/store.js\"), \", add the following.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"import { createStore } from \\\"redux\\\"\\nimport reducers from \\\"./reducers\\\"\\n\\nconst store = createStore(reducers)\\n\\nexport default store\\n\")), mdx(\"p\", null, \"The last thing we need to do to set up Redux is tie our store into our router. Within \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"app/index.js\"), \", we need to wrap our entire app in a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Provider\"), \" component.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-jsx\",\n    \"parentName\": \"pre\"\n  }, \"...\\nimport { Provider } from \\\"react-redux\\\"\\nimport store from \\\"./redux/store\\\"\\n\\n...\\n\\nReactDOM.render(\\n  <Provider store={store}>\\n    <Router history={hashHistory}>\\n      <Route path=\\\"/\\\" component={App}>\\n        <IndexRoute component={Home} />\\n        <Route path=\\\"settings\\\" component={Settings} />\\n      </Route>\\n    </Router>\\n  </Provider>,\\n  document.getElementById(\\\"root\\\")\\n)\\n\")), mdx(\"p\", null, mdx(\"em\", {\n    \"parentName\": \"p\"\n  }, \"A note on capitalization:\"), \" One thing to note is that our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Provider\"), \" is capitalized. Because it is a component that we are using in \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"jsx\"), \", if you do not capitalize it, your app will break. Capital letters are more than a convention: they are the rule.\"), mdx(\"h2\", null, \"Proof of concept\"), mdx(\"p\", null, \"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.\"), mdx(\"p\", null, \"Within our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Login\"), \" component, let's connect our store to our component. We do this with the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"connect\"), \" function that \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"react-redux\"), \" gives us. At the top of our component, import \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"connect\"), \" and at the bottom we have to create a new function, described below the codeblock.\"), mdx(\"p\", null, \"Recall that, for now, to see the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Login\"), \" form, you have to change the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"formState\"), \" in our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Home\"), \" component to \\\"login\\\".\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-jsx\",\n    \"parentName\": \"pre\"\n  }, \"import { connect } from \\\"react-redux\\\"\\n\\n...\\n\\nconst mapStateToProps = state => ({\\n  user: state.user\\n})\\n\\nexport default connect(mapStateToProps)(cssModules(Login, style))\\n\")), mdx(\"p\", null, \"Recall that with one-line ES2015 arrow functions implicitly \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"return\"), \" the value after the arrow. So these two are equivalent:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"const mapStateToProps = state => {\\n  return {\\n    user: state.user,\\n  }\\n}\\n\\nconst mapStateToProps = state => ({\\n  user: state.user,\\n})\\n\")), mdx(\"p\", null, \"The \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"mapStateToProps\"), \" function takes the state of the app from your \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"store\"), \" (recall we set the default value of \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user\"), \" in our reducer to an empty object \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"{}\"), \") and maps that over to the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"props\"), \" of your current component. In this case, we are taking \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"state.user\"), \" from our global \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"store\"), \" and assigning \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"this.props.user\"), \" of our current component to that same value. A more accurate name for this might be \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"mapStateOfStoreToPropsOfComponent\"), \", but that's perhaps a bit too verbose.\"), mdx(\"p\", null, \"To show that this is working, let's add a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"console.log\"), \" within our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"render\"), \" function before we \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"return\"), \" our component.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-jsx\",\n    \"parentName\": \"pre\"\n  }, \"...\\n  render() {\\n    console.log(this.props.user)\\n    return (\\n      ...\\n    )\\n  }\\n\")), mdx(\"p\", null, \"Now, if you change the state of \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"formState\"), \" in your \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"Object {}\\n\")), mdx(\"p\", null, \"The next step is to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"dispatch\"), \" an action with the values from the form that will allow us to change the value of \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"this.props.user\"), \".\"), mdx(\"p\", null, \"We do this by importing our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Actions\"), \" and using the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"dispatch\"), \" function that we get when we \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"connect\"), \" our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Login\"), \" component using \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"react-redux\"), \".\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-jsx\",\n    \"parentName\": \"pre\"\n  }, \"import Actions from \\\"../../redux/actions\\\"\\n  ...\\n\\nexport class Login extends React.Component {\\n  constructor(props) {\\n    super(props)\\n    this.submit = this.submit.bind(this)\\n  }\\n\\n  submit() {\\n    const user = {\\n      email: document.getElementById(\\\"signup-email\\\").value,\\n      password: document.getElementById(\\\"signup-password\\\").value\\n    }\\n    this.props.dispatch(Actions.userLogin(user))\\n  }\\n\\n  render() {\\n    return (\\n      <div className={style.wrapper}>\\n        <div className={style.form}>\\n          ...\\n          <Button\\n            onClick={this.submit}\\n            style={{ width: \\\"100%\\\" }}\\n            type=\\\"primary\\\">\\n            Submit\\n          </Button>\\n        </div>\\n      </div>\\n    )\\n  }\\n}\\n\\n...\\n\")), mdx(\"p\", null, \"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.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"Object {email: \\\"alan@turing.com\\\", password: \\\"badpassword1\\\"}\\n\")), mdx(\"p\", null, \"This worked by taking the values from the inputs, dispatching those values as the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"userLogin\"), \" action, which hits our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user\"), \" reducer, which triggers the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"USER_LOGIN\"), \" type, which assigns \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user\"), \" to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"{ email: action.payload.user.email }\"), \".\"), mdx(\"p\", null, \"You may recall that when \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"props\"), \" are updated, your component automatically updates. In this case, since \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Login\"), \" is connected to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"this.props.user\"), \", which was mapped from \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"state.user\"), \", our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"console.log\"), \" was called again with the updated value.\"), mdx(\"p\", null, \"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.\"));\n}\n;\nMDXContent.isMDXComponent = true;","excerpt":"Actions, Reducers, and Store Proof of concept Connect to API In this section, we create our actions, reducers, and our store. From there, we…","frontmatter":{"title":"Actions, Reducers, and Store","order":18,"active":true,"free":false,"tech":["react","redux"]}}},"pageContext":{"slug":"actions-reducers-and-store","prevNode":{"frontmatter":{"title":"Basics of Redux","active":true,"free":false,"order":17,"tech":["react","redux"]},"fields":{"slug":"basics-of-redux"}},"nextNode":{"frontmatter":{"title":"Login and Authentication: Part 1","active":true,"free":false,"order":19,"tech":["phoenix","elixir","ueberauth"]},"fields":{"slug":"login-and-authentication-part-1"}}}},"staticQueryHashes":["1723017916"]}