{"componentChunkName":"component---src-templates-lesson-js","path":"/phoenix-chat/basics-of-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\": \"Basics of Redux\",\n  \"order\": 17,\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, \"Basics of Redux\"), mdx(\"ul\", null, mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Redux and Flux\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, mdx(\"inlineCode\", {\n    \"parentName\": \"li\"\n  }, \"actions\"), \", \", mdx(\"inlineCode\", {\n    \"parentName\": \"li\"\n  }, \"reducers\"), \", and \", mdx(\"inlineCode\", {\n    \"parentName\": \"li\"\n  }, \"store\"))), mdx(\"p\", null, \"The next step is to log a user in after signup. We're going to handle this with Redux, so now is a good time to go over the basics. If you are not already familiar with Redux, I highly recommend checkout out these \", mdx(\"a\", {\n    \"href\": \"https://egghead.io/series/getting-started-with-redux\",\n    \"parentName\": \"p\"\n  }, \"30 free videos\"), \" sponsored by \", mdx(\"a\", {\n    \"href\": \"http://egghead.io\",\n    \"parentName\": \"p\"\n  }, \"egghead.io\"), \". If you are familiar with Redux, skip ahead to the \\\"Connecting Redux\\\" section.\"), mdx(\"h2\", null, \"What is Redux?\"), mdx(\"p\", null, \"To really understand Redux, you must first understand \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"state\"), \". Think of \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"state\"), \" as the current status of your app. Imagine you're Facebook. You are currently logged in, you have two chat windows open, and you have just launched a modal to upload a new picture.\"), mdx(\"p\", null, \"To generalize, the state of your app could be:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"{\\n  currentUser: \\\"username\\\",\\n  chat: [\\n    { with: \\\"friend1\\\"},\\n    { with: \\\"friend2\\\"}\\n  ],\\n  modal: true,\\n  imageUrl: false\\n}\\n\")), mdx(\"p\", null, \"If you wanted to replicate the exact status of this page at this point in time, all you have to do is set your \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"state\"), \" to all of the necessary conditions. This is extremely powerful, especially when used in conjunction with Redux.\"), mdx(\"p\", null, \"Redux consists of \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"actions\"), \", \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"reducers\"), \", and a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"store\"), \". The concepts around \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"actions\"), \" and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"store\"), \" are easy to understand--the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"reducers\"), \" are a little bit more complicated, but still not especially difficult, and it will become much more clear once we start implementing them.\"), mdx(\"p\", null, \"The basic concept is that Redux keeps your \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"state\"), \" at the highest level of your app, and that every component within your app gets its state from that high-level container, whereas a normal React app will have local state.\"), mdx(\"p\", null, \"TODO image of local state v. redux\"), mdx(\"h2\", null, \"Basics of Flux\"), mdx(\"p\", null, \"Before we go into Redux, we should really discuss \", mdx(\"a\", {\n    \"href\": \"https://facebook.github.io/flux/\",\n    \"parentName\": \"p\"\n  }, \"Flux\"), \". Flux is one of the major innovations behind React, and it enforces uni-directional data flow.\"), mdx(\"p\", null, \"Rather than go into detail here, check out \", mdx(\"a\", {\n    \"href\": \"https://www.youtube.com/embed/nYkdrAPrdcw?list=PLb0IAmt7-GS188xDYE-u1ShQmFFGbrk0v\",\n    \"parentName\": \"p\"\n  }, \"this video\"), \" where Facebook explains the origins of Flux and how it works.\"), mdx(\"p\", null, \"Back in the old days of the internet, we used something jQuery to trigger events that would directly manipulate the DOM. For example, we might have a button in one part of our app that appends a new item to a list, or toggle a class on a particular DOM element.\"), mdx(\"p\", null, \"These events were not tied together in any meaningful way, and any data these components received came from sporadic sources. Tracking down the origin of certain events and data was notoriously difficult.\"), mdx(\"p\", null, \"Flux is an attempt at solving that problem. Rather than allowing your models to send data to many views, Flux enforces hierarchy so your views cannot directly make changes to your data.\"), mdx(\"p\", null, mdx(\"img\", {\n    \"src\": \"/learnphoenix-static-assets/images/action_flow.jpg\",\n    \"alt\": \"action flow\",\n    \"parentName\": \"p\"\n  })), mdx(\"p\", null, \"We will be using Redux, which is a library that is an implementation of Flux.\"), mdx(\"h2\", null, \"Working with data\"), mdx(\"p\", null, \"Every interaction our app will have with our server will be through Redux, and all of our data is passed in to our components through Redux, so this is a good time to talk about how to handle data more generally.\"), mdx(\"p\", null, \"A major long-term problem with web APIs, and one not solved by Redux or Flux, is \\\"over-fetching\\\". Twitter is an example of this, because their API returns a deeply-nested object which always contains more data than your app needs.\"), mdx(\"p\", null, mdx(\"a\", {\n    \"href\": \"https://facebook.github.io/graphql/\",\n    \"parentName\": \"p\"\n  }, \"GraphQL\"), \" and \", mdx(\"a\", {\n    \"href\": \"http://netflix.github.io/falcor/\",\n    \"parentName\": \"p\"\n  }, \"Falcor\"), \" are different approaches of solving this problem. They are more efficient, but require more boilerplate to set up.\"), mdx(\"p\", null, \"GraphQL allow you to tell the server specifically what you want and return only that. It is also much more declarative and the server figures out the most efficient way to prepare your data. It also takes more boilerplate code and is only really necessary for apps that have such scale that they need to use it.\"), mdx(\"p\", null, \"At this point in our app, GraphQL is overkill, and we'll just stick to a simple JSON API. Refactoring to use GraphQL and Relay is very doable and we can cross that bridge if it becomes necessary.\"), mdx(\"p\", null, \"With a JSON API, you send a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"request\"), \" to a server at a specific url with the parameters that the API needs to complete the request. An example request might look like the code below, where we are simply requesting data from \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"http://github.com/data.json\"), \".\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"fetch(\\\"http://github.com/data.json\\\", {\\n  method: \\\"GET\\\",\\n})\\n  .then(function (res) {\\n    // Response here\\n  })\\n  .catch(function (err) {\\n    // If error, error here\\n  })\\n\")), mdx(\"p\", null, \"You've probably heard a lot about \\\"REST\\\" APIs. People will argue endlessly about the \", mdx(\"em\", {\n    \"parentName\": \"p\"\n  }, \"real\"), \" definition of what it means to be \\\"RESTful\\\", and that's because REST does not have an official definition--it's a description of an architecture style, not a protocol.\"), mdx(\"p\", null, \"But the important part is that REST APIs are stateless, so you pass the state to the API as parameters. For example, if you want to create a new user with a REST API, you pass the user details as the parameters to the endpoint. Most of the APIs you've dealt with are REST APIs, so the concept should be at least implicitly familiar.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"fetch(\\\"http://learnphoenix.io/create\\\", {\\n  method: \\\"POST\\\",\\n  body: \\\"first=Alan&last=Turing&password=badpassword1\\\",\\n})\\n  .then(function (res) {\\n    // Response here\\n  })\\n  .catch(function (err) {\\n    // If error, error here\\n  })\\n\")), mdx(\"p\", null, \"Our Phoenix backend is a REST API, and we will use Phoenix to handle requests that we send from our frontend, as we have already demonstrated when creating a user.\"), mdx(\"h2\", null, \"Basics of Redux\"), mdx(\"p\", null, \"Redux is Flux-ish, with some additional features. The code behind Redux is surprisingly small, and it's really just a well-thought-out design pattern. The main principle of Redux is that you don't keep local state in your components--all of your state is held in one place at the highest-possible level of your app and passed down.\"), mdx(\"p\", null, \"The way you use it is to wrap your entire app in a Redux \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Provider\"), \" (explained in the next lesson) so that you can later connect each of your React components to this global data source (called a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"store\"), \").\"), mdx(\"p\", null, \"The \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"store\"), \" is dumb. It's just an object that holds your state.\"), mdx(\"p\", null, \"In order to process the data and make any changes to your data, you need to pass it through a series of \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"reducers\"), \". These reducers are actually quite simple and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"reduce\"), \" is an important function in functional programming.\"), mdx(\"p\", null, \"If you are not familiar with what a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"reducer\"), \" does, think of it as taking a long list of information and applying some transformation to each item in order. For example, say you have a list of numbers:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"var list = [3, 1, -3, 5, 1]\\n\")), mdx(\"p\", null, \"If you wanted to combine all of these values into a single value by adding them you could write a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"for\"), \" loop to go over each of them, but that would not be very efficient. Instead, you can write a reducer that takes in the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"previous\"), \" and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"current\"), \" values as parameters and combines them within the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"reduce\"), \" function.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"var list = [3, 1, -3, 5, 1]\\n\\nvar output = list.reduce(function (previous, current) {\\n  return previous + current\\n})\\nconsole.log(output) // -> 7\\n\")), mdx(\"p\", null, \"Now, think of this in terms of Redux. Let's say we have a list of actions:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"var list = [\\n  { modal: open },\\n  { modal: close },\\n  { modal: open },\\n  {\\n    chat: {\\n      name: \\\"Eric\\\",\\n      isOpen: true,\\n    },\\n  },\\n  {\\n    chat: {\\n      name: \\\"Eric\\\",\\n      isOpen: false,\\n    },\\n  },\\n  {\\n    chat: {\\n      name: \\\"John\\\",\\n      isOpen: true,\\n    },\\n  },\\n]\\n\")), mdx(\"p\", null, \"What is the current status of this app? Is the modal open or closed? Who has an active chat window? As you will see when we start building our reducers, we can \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"reduce\"), \" a list of actions to the current state of the application.\"), mdx(\"p\", null, \"Reducers listen to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"actions\"), \" and mutates some piece of state based on the action.\"), mdx(\"p\", null, \"For example, in a \\\"todo\\\" app, the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"action\"), \" might be something like \\\"create a new list item\\\" or \\\"mark as completed\\\". The action passes any relevant data to the reducer, which changes the current state of the app to reflect the change that the action wanted made. \\\"Mark as completed\\\", for example, would change the specific item in your state and change the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"completed\"), \" key to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"true\"), \".\"), mdx(\"p\", null, \"Whenever the old state does not equal the new state, Redux will fire all of the event listeners and update all of the data in your app that was listening for something that got changed. This means that if you changed something in the todo list, your profile page would not necessarily need to be updated because it does not contain any data related to the todo list.\"), mdx(\"p\", null, mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"action\"), \" is a way to trigger those reducers. They are, by default, synchronous. Since much of what you will be doing in a web app is asynchronous, you will quickly need some additional plugins, such as \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"thunk\"), \" and potentially other middleware.\"), mdx(\"p\", null, \"Actions allow you to be more declarative. If you are not familiar with the difference between declarative and imperative, \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"declarative\"), \" means saying what you want, while \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"imperative\"), \" means describing how you will do it. For example, a declarative approach to data fetching would be something like GraphQL, in which you tell your backend what data you want and GraphQL sorts out the details of how to get that data for you.\"), mdx(\"h2\", null, \"Setting up Redux\"), mdx(\"p\", null, \"The first thing we need to do is add \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"redux\"), \" as a dependency, as well as several other Redux-related dependencies.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ npm install --save redux react-redux react-router-redux\\n\")), mdx(\"p\", null, \"The \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"react-redux\"), \" module binds Redux to React and is necessary to get Redux working with React. The \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"redux\"), \" module contains all of the core functionality that we need. The \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"react-router-redux\"), \" wraps our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"react-router\"), \" so we can keep track of the state of our routes--without this, our routes are considered a side-effect.\"), mdx(\"p\", null, \"We're going to keep all of our Redux-related files in a new \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"app/redux\"), \" directory. Eventually we will have too many actions and reducers to fit in a single file, but that is easy to refactor and we can do that when it becomes necessary.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ mkdir app/redux\\n\")), mdx(\"p\", null, \"Within this directory, we will have three files: \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"actions.js\"), \", \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"reducers.js\"), \", and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"store.js\"), \".\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ touch app/redux/{actions,reducers,store}.js\\n\")), mdx(\"p\", null, \"We will go over each of these in more detail in the next section.\"));\n}\n;\nMDXContent.isMDXComponent = true;","excerpt":"Basics of Redux Redux and Flux actions ,  reducers , and  store The next step is to log a user in after signup. We're going to handle this…","frontmatter":{"title":"Basics of Redux","order":17,"active":true,"free":false,"tech":["react","redux"]}}},"pageContext":{"slug":"basics-of-redux","prevNode":{"frontmatter":{"title":"Connect the API","active":true,"free":false,"order":16,"tech":["react"]},"fields":{"slug":"connect-the-api"}},"nextNode":{"frontmatter":{"title":"Actions, Reducers, and Store","active":true,"free":false,"order":18,"tech":["react","redux"]},"fields":{"slug":"actions-reducers-and-store"}}}},"staticQueryHashes":["1723017916"]}