{"componentChunkName":"component---src-templates-lesson-js","path":"/phoenix-chat/connect-the-api","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\": \"Connect the API\",\n  \"order\": 16,\n  \"free\": false,\n  \"active\": true,\n  \"tech\": [\"react\"]\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, \"Connect the API\"), mdx(\"ul\", null, mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Making an API call with \", mdx(\"inlineCode\", {\n    \"parentName\": \"li\"\n  }, \"fetch\")), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Creating users from the frontend\")), mdx(\"p\", null, \"We now have a functional backend that can take \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"POST\"), \" requests and create a user. That user can't sign in yet, but we can at least create one and check the Phoenix logs to make sure it worked. We're going to use the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Signup\"), \" component to create a user and send that user to our Phoenix API.\"), mdx(\"p\", null, \"We have not yet implemented Redux, so we are just going to make the API call locally from within our component. This is not how we are going to make these calls in the long-run, but it is the simplest way to make these calls and demonstrate that our frontend and backend are talking to each other.\"), mdx(\"p\", null, \"We're also going to create a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Chat\"), \" component that we will use extensively in later lessons as our admin panel.\"), mdx(\"h2\", null, \"Making HTTP calls\"), mdx(\"p\", null, \"The first thing we should do is add an HTTP client. There are a lot of options, but we're going to use \", mdx(\"a\", {\n    \"href\": \"https://github.com/github/fetch\",\n    \"parentName\": \"p\"\n  }, \"fetch\"), \", which is a polyfill for the soon-to-be native promise-based \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"fetch\"), \" API. Many browsers already support \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"fetch\"), \" without a polyfill.\"), mdx(\"p\", null, \"What \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"fetch\"), \" will allow us to do is make an HTTP call to get a resource from a server--in our case, the Phoenix API.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ npm install --save-dev whatwg-fetch\\n\")), mdx(\"p\", null, \"Since we only have signup working on our server, we only need to worry about sending a request to create a user. If you go back to the Phoenix backend and run \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"mix phoenix.routes\"), \", you'll see a route that looks like the following.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ mix phoenix.routes\\n\\n...\\nuser_path  POST    /api/users      Firestorm.UserController :create\\n...\\n\")), mdx(\"p\", null, \"This is telling us that we need to send a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"POST\"), \" request to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"localhost:4000/api/users\"), \" to create a new user. Let's head over to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Signup\"), \" to add \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"fetch\"), \" and get our form ready to make a call to our backend.\"), mdx(\"p\", null, \"New browsers have \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"fetch\"), \" as a native function, but some do not. In order to accommodate those older browsers, we need to add fetch to our webpack configuration. We're going to add it as an entry point, so all our requests get routed through the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"whatwg-fetch\"), \" polyfill before bundling.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"...\\n\\nmodule.exports = {\\n  devtool: \\\"eval\\\",\\n  entry: [\\n    \\\"whatwg-fetch\\\",\\n    \\\"webpack-dev-server/client?http://localhost:3000\\\",\\n    \\\"./app/index\\\"\\n  ],\\n  ...\\n}\\n\")), mdx(\"p\", null, mdx(\"strong\", {\n    \"parentName\": \"p\"\n  }, \"Remember\"), \" you must now restart your server. Any time you make a change to your webpack configuration, you must restart your server.\"), mdx(\"p\", null, \"Then we can use \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"fetch\"), \" globally without worrying about old browsers. Let's update our submit function to use \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"fetch\"), \" to make a request to our API endpoint (explanation below the code).\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"...\\n\\n  ...\\n  submit() {\\n    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({ test: \\\"not going to work\\\" })\\n    })\\n    .then((res) => { return res.json() })\\n    .then((res) => {\\n      console.log(res);\\n    })\\n    .catch((err) => {\\n      console.warn(err);\\n    })\\n  }\\n  ...\\n\")), mdx(\"p\", null, \"What we're doing in the code above is setting our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Button\"), \" to call the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"submit\"), \" function when it's clicked. Then we call \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"fetch\"), \" with a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"POST\"), \" method to our API endpoint with an object that won't work.\"), mdx(\"p\", null, \"Because \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"fetch\"), \" is promise-based, we have access to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \".then\"), \" and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \".catch\"), \". Anything within a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \".then\"), \" function is run if the HTTP call was successful and anything within \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \".catch\"), \" is run if the call was a failure. Since we're sending a bad request, we should expect our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"console.log\"), \" within the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \".catch\"), \" to run.\"), mdx(\"p\", null, \"One thing worth noting is that we are \", mdx(\"em\", {\n    \"parentName\": \"p\"\n  }, \"chaining\"), \" our promises to include a step that pulls out the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"JSON\"), \" that we receive from our server (\", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"return res.json()\"), \"). Many HTTP clients do this for you, but \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"fetch\"), \" does not.\"), mdx(\"p\", null, \"We are also sending with \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"headers\"), \" that tell our backend that we are sending \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"json\"), \" and that we are expecting \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"json\"), \" in return. But we can't just send raw \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"json\"), \", so we need to use \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"JSON.stringify()\"), \" to turn our object into a string so we can pass that string to our server.\"), mdx(\"p\", null, \"Go ahead and open the signup modal and click the submit button.\"), mdx(\"p\", null, \"Now check your browser console and you should see an error with the value \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"POST http://localhost:4000/api/users 400 (Bad Request)\"), \". Great! That's what we wanted.\"), mdx(\"p\", null, \"You should also check your Phoenix terminal, where you should see output along the lines of the following.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"[debug] Simple CORS request from Origin 'http://localhost:3000' is allowed\\n[debug] Processing by PhoenixChat.UserController.create/2\\n  Parameters: %{\\\"test\\\" => \\\"not going to work\\\"}\\n  Pipelines: [:api]\\n  ...\\n\")), mdx(\"p\", null, \"That's exactly the error we wanted to see. Phoenix was expecting the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user\"), \" key, but got \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"test\"), \" instead.\"), mdx(\"p\", null, \"So now let's connect our submission with the form and submit a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user\"), \" to Phoenix. Remember, we will eventually use \", mdx(\"a\", {\n    \"href\": \"https://facebook.github.io/react/docs/forms.html#controlled-components\",\n    \"parentName\": \"p\"\n  }, \"controlled components\"), \", but since we just want to get something up and running as quickly as possible, we're just going to pull the values straight from the inputs.\"), mdx(\"p\", null, \"We can do that by changing our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"submit\"), \" function to the following.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\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    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) => { return res.json() })\\n    .then((res) => {\\n      console.log(res);\\n    })\\n    .catch((err) => {\\n      console.warn(err);\\n    })\\n  }\\n  ...\\n\")), mdx(\"p\", null, \"We're going to find the elements with the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"id\"), \" that we want and extract the value. We put all those values into a new \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user\"), \" object, and then pass that object into our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"post\"), \" call as a parameter.\"), mdx(\"p\", null, \"Recall that in ES6, if the value in an object is the same as the key, you can simply pass a single variable. So in the example above, we are passing \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user\"), \" instead of \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user: user\"), \".\"), mdx(\"p\", null, \"Go ahead and fill out the form and press the button.\"), mdx(\"p\", null, \"In your browser console, you should see \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"status: 201\"), \" and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"statusText: \\\"Created\\\"\"), \". And if you check your Phoenix output, you'll see it was successful there as well.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"Response {type: \\\"cors\\\", url: \\\"http://localhost:4000/api/users\\\", status: 201, ok: true, statusText: \\\"Created\\\"...}\\n\")), mdx(\"p\", null, \"And if you check your browser console, you should see an object with the key \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"data\"), \" that contains the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"email\"), \", \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"id\"), \", and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"username\"), \" of the username you just created.\"), mdx(\"p\", null, \"And that's all there is to it. Now we have to go back to Phoenix to give our users the ability to log in. But before we do that, let's create a new \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Chat\"), \" component that will sit behind our user authentication, as well as a bit more styling.\"), mdx(\"h2\", null, \"Chat component\"), mdx(\"p\", null, \"Let's create a new \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Chat\"), \" component that will function as our admin interface for our app.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ mkdir app/components/Chat\\n$ touch app/components/Chat/{index.js,spec.js,style.css,README.md}\\n\")), mdx(\"p\", null, \"Then within \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Chat/index.js\"), \", add the following:\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"import React from \\\"react\\\"\\nimport cssModules from \\\"react-css-modules\\\"\\nimport style from \\\"./style.css\\\"\\n\\nimport { default as Sidebar } from \\\"../Sidebar\\\"\\n\\nexport class Chat extends React.Component {\\n  render() {\\n    return (\\n      <div>\\n        <Sidebar />\\n        <div className={style.chatWrapper}>chat me</div>\\n        {this.props.children}\\n      </div>\\n    )\\n  }\\n}\\n\\nexport default cssModules(Chat, style)\\n\")), mdx(\"p\", null, \"And add the wrapper to the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"style.css\"), \" file.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-css\",\n    \"parentName\": \"pre\"\n  }, \".chatWrapper {\\n  margin-left: 300px;\\n}\\n\")), mdx(\"p\", null, \"And add a simple test to make sure it renders properly.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"import React from \\\"react\\\"\\nimport expect from \\\"expect\\\"\\nimport { shallow } from \\\"enzyme\\\"\\n\\nimport { Chat } from \\\"./\\\"\\n\\nconst props = {}\\n\\ndescribe(\\\"<Chat />\\\", () => {\\n  it(\\\"should render\\\", () => {\\n    const renderedComponent = shallow(<Chat {...props} />)\\n    expect(renderedComponent.is(\\\"div\\\")).toEqual(true)\\n  })\\n})\\n\")), mdx(\"p\", null, \"So now we have the ability to create users, but they can't sign in. We're also handling our API calls in our local component, which is bad practice, so it's about time we introduce Redux.\"));\n}\n;\nMDXContent.isMDXComponent = true;","excerpt":"Connect the API Making an API call with  fetch Creating users from the frontend We now have a functional backend that can take  POST…","frontmatter":{"title":"Connect the API","order":16,"active":true,"free":false,"tech":["react"]}}},"pageContext":{"slug":"connect-the-api","prevNode":{"frontmatter":{"title":"Login and Signup Forms","active":true,"free":false,"order":15,"tech":["react"]},"fields":{"slug":"login-and-signup-forms"}},"nextNode":{"frontmatter":{"title":"Basics of Redux","active":true,"free":false,"order":17,"tech":["react","redux"]},"fields":{"slug":"basics-of-redux"}}}},"staticQueryHashes":["1723017916"]}