fetchWe now have a functional backend that can take 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 Signup component to create a user and send that user to our Phoenix API.
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.
We're also going to create a Chat component that we will use extensively in later lessons as our admin panel.
The first thing we should do is add an HTTP client. There are a lot of options, but we're going to use fetch, which is a polyfill for the soon-to-be native promise-based fetch API. Many browsers already support fetch without a polyfill.
What fetch will allow us to do is make an HTTP call to get a resource from a server--in our case, the Phoenix API.
$ npm install --save-dev whatwg-fetchSince 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 mix phoenix.routes, you'll see a route that looks like the following.
$ mix phoenix.routes...user_path POST /api/users Firestorm.UserController :create...This is telling us that we need to send a POST request to localhost:4000/api/users to create a new user. Let's head over to Signup to add fetch and get our form ready to make a call to our backend.
New browsers have 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 whatwg-fetch polyfill before bundling.
...module.exports = { devtool: "eval", entry: [ "whatwg-fetch", "webpack-dev-server/client?http://localhost:3000", "./app/index" ], ...}Remember you must now restart your server. Any time you make a change to your webpack configuration, you must restart your server.
Then we can use fetch globally without worrying about old browsers. Let's update our submit function to use fetch to make a request to our API endpoint (explanation below the code).
... ... submit() { fetch("http://localhost:4000/api/users", { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json" }, body: JSON.stringify({ test: "not going to work" }) }) .then((res) => { return res.json() }) .then((res) => { console.log(res); }) .catch((err) => { console.warn(err); }) } ...What we're doing in the code above is setting our Button to call the submit function when it's clicked. Then we call fetch with a POST method to our API endpoint with an object that won't work.
Because fetch is promise-based, we have access to .then and .catch. Anything within a .then function is run if the HTTP call was successful and anything within .catch is run if the call was a failure. Since we're sending a bad request, we should expect our console.log within the .catch to run.
One thing worth noting is that we are chaining our promises to include a step that pulls out the JSON that we receive from our server (return res.json()). Many HTTP clients do this for you, but fetch does not.
We are also sending with headers that tell our backend that we are sending json and that we are expecting json in return. But we can't just send raw json, so we need to use JSON.stringify() to turn our object into a string so we can pass that string to our server.
Go ahead and open the signup modal and click the submit button.
Now check your browser console and you should see an error with the value POST http://localhost:4000/api/users 400 (Bad Request). Great! That's what we wanted.
You should also check your Phoenix terminal, where you should see output along the lines of the following.
[debug] Simple CORS request from Origin 'http://localhost:3000' is allowed[debug] Processing by PhoenixChat.UserController.create/2 Parameters: %{"test" => "not going to work"} Pipelines: [:api] ...That's exactly the error we wanted to see. Phoenix was expecting the user key, but got test instead.
So now let's connect our submission with the form and submit a user to Phoenix. Remember, we will eventually use 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.
We can do that by changing our submit function to the following.
... submit() { const user = { username: document.getElementById("signup-username").value, email: document.getElementById("signup-email").value, password: document.getElementById("signup-password").value } fetch("http://localhost:4000/api/users", { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json" }, body: JSON.stringify({ user }) }) .then((res) => { return res.json() }) .then((res) => { console.log(res); }) .catch((err) => { console.warn(err); }) } ...We're going to find the elements with the id that we want and extract the value. We put all those values into a new user object, and then pass that object into our post call as a parameter.
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 user instead of user: user.
Go ahead and fill out the form and press the button.
In your browser console, you should see status: 201 and statusText: "Created". And if you check your Phoenix output, you'll see it was successful there as well.
Response {type: "cors", url: "http://localhost:4000/api/users", status: 201, ok: true, statusText: "Created"...}And if you check your browser console, you should see an object with the key data that contains the email, id, and username of the username you just created.
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 Chat component that will sit behind our user authentication, as well as a bit more styling.
Let's create a new Chat component that will function as our admin interface for our app.
$ mkdir app/components/Chat$ touch app/components/Chat/{index.js,spec.js,style.css,README.md}Then within Chat/index.js, add the following:
import React from "react"import cssModules from "react-css-modules"import style from "./style.css"import { default as Sidebar } from "../Sidebar"export class Chat extends React.Component { render() { return ( <div> <Sidebar /> <div className={style.chatWrapper}>chat me</div> {this.props.children} </div> ) }}export default cssModules(Chat, style)And add the wrapper to the style.css file.
.chatWrapper { margin-left: 300px;}And add a simple test to make sure it renders properly.
import React from "react"import expect from "expect"import { shallow } from "enzyme"import { Chat } from "./"const props = {}describe("<Chat />", () => { it("should render", () => { const renderedComponent = shallow(<Chat {...props} />) expect(renderedComponent.is("div")).toEqual(true) })})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.
Previous: Login and Signup FormsNext: Basics of Redux