{"componentChunkName":"component---src-templates-lesson-js","path":"/phoenix-chat/move-logic-to-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\": \"Move Logic to Redux\",\n  \"order\": 21,\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, \"Move Logic to Redux\"), mdx(\"ul\", null, mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Asynchronous actions\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Updating the user\")), mdx(\"p\", null, \"So now that we understand some of the concepts of Redux and have our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"store\"), \" connected to our app, we can start building our app for real. The first thing we should connect is our user.\"), mdx(\"p\", null, \"We want to be able to:\"), mdx(\"ul\", null, mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"create a new user\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"log that user in\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"authenticate that user\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"log that user out.\")), mdx(\"p\", null, \"Since the user is something that we will want to have access to in our entire app, it makes sense to hold this value in the highest-order component we have and pass that value down to all children, which in this case is our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"App\"), \" component. But since we're using Redux, we can keep that value in our global \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"store\"), \" and pull it out using \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"connect\"), \".\"), mdx(\"h2\", null, \"Asynchronous actions\"), mdx(\"p\", null, \"Before we get much further, configure our app to work properly with Redux. The first thing we should reconfigure is our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Signup\"), \" component and the associated action. We want to move our asynchronous request out of our component and into our action, and we want to connect our component to Redux.\"), mdx(\"p\", null, \"But Redux doesn't support asynchronous calls without middleware. That's where we need something like \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"thunk\"), \" comes in. From the docs:\"), mdx(\"blockquote\", null, mdx(\"p\", {\n    \"parentName\": \"blockquote\"\n  }, \"A thunk is a function that wraps an expression to delay its evaluation.\")), mdx(\"p\", null, \"It's a handy way for us to make asynchronous calls within our actions.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ npm install --save redux-thunk\\n\")), mdx(\"p\", null, \"And in order to apply that middleware, we need to add some additional configuration to our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"store\"), \". Within \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"store.js\"), \" we need to import a few more functions and add \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"thunk\"), \" to an \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"applyMiddleware\"), \" call. We are also using \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"compose\"), \", which allows us to create a wrapper function that composes of other functions in order.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"import { createStore, compose, applyMiddleware } from \\\"redux\\\"\\nimport thunk from \\\"redux-thunk\\\"\\nimport reducers from \\\"./reducers\\\"\\n\\nconst middlewares = [thunk]\\n\\nconst createStoreWrapper = compose(applyMiddleware(...middlewares))(createStore)\\n\\nconst store = createStoreWrapper(reducers)\\n\\nexport default store\\n\")), mdx(\"p\", null, \"Now that we've applied our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"thunk\"), \" middleware, we can start running asynchronous actions from our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Actions\"), \". The first one we want to change is \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"userNew\"), \".\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"...\\n\\nActions.userNew = function userNew(user) {\\n  return dispatch => fetch(\\\"http://localhost:4000/api/users\\\", {\\n    method: \\\"POST\\\",\\n    headers: {\\n      Accept: \\\"application/json\\\",\\n      \\\"Content-Type\\\": \\\"application/json\\\"\\n    },\\n    body: JSON.stringify({ user })\\n  })\\n  .then((res) => {\\n    return res.json()\\n  })\\n  .then((res) => {\\n    // TODO: More on this later\\n    console.log(res)\\n  })\\n  .catch((err) => {\\n    console.warn(err)\\n  })\\n}\\n...\\n\")), mdx(\"p\", null, \"Here we are returning a function that takes in \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"dispatch\"), \" as a parameter (used by \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"thunk\"), \") and makes an asynchronous call to our server. If there is an error, we log the error.\"), mdx(\"p\", null, \"We should also change the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"userLogin\"), \" action to make a call to our backend. If you go to your Phoenix backend and check \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"mix phoenix.routes\"), \" you'll see the route for login (\", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"/auth/identity/callback\"), \").\"), mdx(\"p\", null, \"You'll notice a few things different about this action. For one, we are taking the token we receive from the server and saving it to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"localStorage\"), \". If you don't know what \", mdx(\"a\", {\n    \"href\": \"https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage\",\n    \"parentName\": \"p\"\n  }, \"localStorage\"), \" is, you can think of it as the better version of cookies, which are pieces of information you can store on the browser that can only be accessed by the website that sets them. In fact, \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"localStorage\"), \" is supposed to be the replacement for cookies.\"), mdx(\"p\", null, \"After we set the token to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"localStorage\"), \", we \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"dispatch\"), \" an action to our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"reducer\"), \". Recall that our reducer is already set up to handle a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"USER_LOGIN\"), \" action.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"Actions.userLogin = function userLogin(user) {\\n  return dispatch =>\\n    fetch(\\\"http://localhost:4000/auth/identity/callback\\\", {\\n      method: \\\"POST\\\",\\n      headers: {\\n        Accept: \\\"application/json\\\",\\n        \\\"Content-Type\\\": \\\"application/json\\\",\\n      },\\n      body: JSON.stringify({\\n        email: user.email,\\n        password: user.password,\\n      }),\\n    })\\n      .then(res => {\\n        return res.json()\\n      })\\n      .then(res => {\\n        /* If success, log the user in */\\n        localStorage.token = res.data.token\\n        /* Then send action to reducer */\\n        dispatch({\\n          type: \\\"USER_LOGIN\\\",\\n          payload: {\\n            user: res.data,\\n          },\\n        })\\n      })\\n      .catch(err => {\\n        console.warn(err)\\n      })\\n}\\n\")), mdx(\"p\", null, \"If you're a security nut, you can be extra careful and store your token in a session cookie with an \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"httpOnly\"), \" flag. This will prevent XSS attacks and side channel (BREACH) attacks. That said, \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"localStorage\"), \" is more common and perfectly fine for our purposes.\"), mdx(\"p\", null, \"Now within our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user\"), \" reducer, we want to set the value of our user to the value returned by the server. While we're at it, let's add some default values for our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user\"), \" so we don't run into errors later when we assign these values to DOM elements via \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"props\"), \" and also destructure our payload for easier reading.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"...\\n\\nfunction user(state = {\\n  email: \\\"\\\",\\n  username: \\\"\\\",\\n  id: \\\"\\\"\\n}, action) {\\n  switch (action.type) {\\n    case \\\"USER_NEW\\\":\\n      return Object.assign({}, state, {\\n        email: action.payload.user.email,\\n        username: action.payload.user.username,\\n        id: action.payload.user.id\\n      })\\n    case \\\"USER_LOGIN\\\":\\n      return Object.assign({}, state, {\\n        email: action.payload.user.email,\\n        username: action.payload.user.username,\\n        id: action.payload.user.id\\n      })\\n    default: return state\\n  }\\n}\\n\\n...\\n\")), mdx(\"p\", null, \"Let's also update our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"userNew\"), \" function to handle the response from our server.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"...\\nActions.userNew = function userNew(user) {\\n  return dispatch => fetch(\\\"http://localhost:4000/api/users\\\", {\\n    method: \\\"POST\\\",\\n    headers: {\\n      Accept: \\\"application/json\\\",\\n      \\\"Content-Type\\\": \\\"application/json\\\"\\n    },\\n    body: JSON.stringify({ user })\\n  })\\n  .then((res) => {\\n    return res.json()\\n  })\\n  .then((res) => {\\n    /* If success, log the user in */\\n    localStorage.token = res.data.token\\n    /* Then send action to reducer */\\n    dispatch({\\n      type: \\\"USER_NEW\\\",\\n      payload: {\\n        user: res.data\\n      }\\n    })\\n  })\\n  .catch((err) => {\\n    console.warn(err)\\n  })\\n}\\n...\\n\")), mdx(\"h2\", null, \"Connecting the login form\"), mdx(\"p\", null, \"Now that we have everything in place on the backend to handle user login, let's send off the request. Recall that we already set up our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Login\"), \" component to send the request via redux--we just previously hadn't sent the http request.\"), mdx(\"p\", null, \"Go ahead and login with valid credentials (the account you created earlier, or a new one) and you'll see the returned username and email from the server.\"), mdx(\"p\", null, \"What's more, if you check \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"localStorage.token\"), \" in your browser console, you'll see your current, valid JSON web token that we will later use for authentication.\"), mdx(\"h2\", null, \"Connecting the signup form\"), mdx(\"p\", null, \"Since login is working with Redux, we should change our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Signup\"), \" to use the Redux action as well. First import \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"connect\"), \" and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Actions\"), \" from Redux, then we need to replace the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"fetch\"), \" call with a dispatched Redux action and connect our component in our export.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"import React from \\\"react\\\"\\nimport cssModules from \\\"react-css-modules\\\"\\nimport { connect } from \\\"react-redux\\\"\\nimport style from \\\"./style.css\\\"\\nimport Actions from \\\"../../redux/actions\\\"\\n\\n...\\n\\nexport class Signup extends React.Component {\\n  constructor(props) {\\n    super(props)\\n    this.submit = this.submit.bind(this)\\n  }\\n\\n  submit() {\\n    const user = {\\n      username: document.getElementById(\\\"signup-username\\\").value,\\n      email: document.getElementById(\\\"signup-email\\\").value,\\n      password: document.getElementById(\\\"signup-password\\\").value\\n    }\\n    this.props.dispatch(Actions.userNew(user))\\n  }\\n\\n  ...\\n}\\n\\nexport default connect()(cssModules(Signup, style))\\n\")), mdx(\"p\", null, \"Now when you submit your form, you're dispatching the action through Redux instead of through the form component. If you try it with a new username and email, you should see the same successful output in your browser console.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"> Fetch complete: POST \\\"http://localhost:4000/api/users\\\".\\n> Object {data: Object}\\n\")), mdx(\"h2\", null, \"Toggling between signup/login forms\"), mdx(\"p\", null, \"Now is a good time to refactor our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Home\"), \" component to allow us to easily toggle between login and signup forms. First, let's create a new function that allows us to toggle the state.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"...\\nexport class Home extends React.Component {\\n  constructor(props) {\\n    super(props)\\n    this.state = {\\n      formState: \\\"login\\\"\\n    }\\n    this.setFormState = this.setFormState.bind(this)\\n  }\\n\\n  setFormState(formState) {\\n    this.setState({ formState })\\n  }\\n...\\n}\\n\")), mdx(\"p\", null, \"Then let's create a function that determines the content below our form that when clicked will change the state of our form.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"...\\nexport class Home extends React.Component {\\n  constructor(props) {\\n    super(props)\\n    this.state = {\\n      formState: \\\"login\\\"\\n    }\\n    this.setFormState = this.setFormState.bind(this)\\n  }\\n\\n  ...\\n\\n  renderToggleContent() {\\n    switch (this.state.formState) {\\n      case \\\"login\\\":\\n        return (\\n          <div\\n            className={style.changeLink}\\n            onClick={() => this.setFormState(\\\"signup\\\")}>\\n            Need an account? Signup.\\n          </div>\\n        )\\n      case \\\"signup\\\":\\n        return (\\n          <div\\n            className={style.changeLink}\\n            onClick={() => this.setFormState(\\\"login\\\")}>\\n            Have an account? Login.\\n          </div>\\n        )\\n      default: return null\\n    }\\n  }\\n\\n  render() {\\n    return (\\n      <div className={style.leader}>\\n        <h1 className={style.title}>Phoenix Chat</h1>\\n        { this.state.formState === \\\"signup\\\" ? <Signup /> : null }\\n        { this.state.formState === \\\"login\\\" ? <Login /> : null }\\n        { this.renderToggleContent() }\\n        <img\\n          role=\\\"presentation\\\"\\n          className={style.circles}\\n          src=\\\"/learnphoenix-static-assets/images/circles-full.png\\\" />\\n      </div>\\n    )\\n  }\\n}\\n\")), mdx(\"p\", null, \"One thing that you will often see in React code is the use of \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"bind\"), \" to pass a value to your function using JSX. Now that we have ES2015, we can use arrow functions, which automatically bind to the context \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"this\"), \". So for example, the two onClick functions below are the same:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"// ES2015, and what we will use\\nonClick={() => this.setFormState(\\\"login\\\")}>\\n\\n// ES5\\nonClick={this.setFormState.bind(this, \\\"login\\\")}\\n\")), mdx(\"p\", null, \"Also note that if you need access to the event, you will need to pass it as a parameter if you use ES2015 syntax.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"// ES2015 syntax, passing event as second parameter\\nonClick={e => this.setFormState(\\\"login\\\", e)}\\n\")), mdx(\"p\", null, \"And now, when you click on the link, it toggles the form. Granted, it's not styled, but we can do that later.\"));\n}\n;\nMDXContent.isMDXComponent = true;","excerpt":"Move Logic to Redux Asynchronous actions Updating the user So now that we understand some of the concepts of Redux and have our  store…","frontmatter":{"title":"Move Logic to Redux","order":21,"active":true,"free":false,"tech":["react","redux"]}}},"pageContext":{"slug":"move-logic-to-redux","prevNode":{"frontmatter":{"title":"Login and Authentication: Part 2","active":true,"free":false,"order":20,"tech":["phoenix","elixir","ueberauth"]},"fields":{"slug":"login-and-authentication-part-2"}},"nextNode":{"frontmatter":{"title":"Check Login Status","active":true,"free":false,"order":22,"tech":["react","redux"]},"fields":{"slug":"check-login-status"}}}},"staticQueryHashes":["1723017916"]}