So now that we understand some of the concepts of Redux and have our store connected to our app, we can start building our app for real. The first thing we should connect is our user.
We want to be able to:
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 App component. But since we're using Redux, we can keep that value in our global store and pull it out using connect.
Before we get much further, configure our app to work properly with Redux. The first thing we should reconfigure is our 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.
But Redux doesn't support asynchronous calls without middleware. That's where we need something like thunk comes in. From the docs:
A thunk is a function that wraps an expression to delay its evaluation.
It's a handy way for us to make asynchronous calls within our actions.
$ npm install --save redux-thunkAnd in order to apply that middleware, we need to add some additional configuration to our store. Within store.js we need to import a few more functions and add thunk to an applyMiddleware call. We are also using compose, which allows us to create a wrapper function that composes of other functions in order.
import { createStore, compose, applyMiddleware } from "redux"import thunk from "redux-thunk"import reducers from "./reducers"const middlewares = [thunk]const createStoreWrapper = compose(applyMiddleware(...middlewares))(createStore)const store = createStoreWrapper(reducers)export default storeNow that we've applied our thunk middleware, we can start running asynchronous actions from our Actions. The first one we want to change is userNew.
...Actions.userNew = function userNew(user) { return dispatch => 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) => { // TODO: More on this later console.log(res) }) .catch((err) => { console.warn(err) })}...Here we are returning a function that takes in dispatch as a parameter (used by thunk) and makes an asynchronous call to our server. If there is an error, we log the error.
We should also change the userLogin action to make a call to our backend. If you go to your Phoenix backend and check mix phoenix.routes you'll see the route for login (/auth/identity/callback).
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 localStorage. If you don't know what 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, localStorage is supposed to be the replacement for cookies.
After we set the token to localStorage, we dispatch an action to our reducer. Recall that our reducer is already set up to handle a USER_LOGIN action.
Actions.userLogin = function userLogin(user) { return dispatch => fetch("http://localhost:4000/auth/identity/callback", { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json", }, body: JSON.stringify({ email: user.email, password: user.password, }), }) .then(res => { return res.json() }) .then(res => { /* If success, log the user in */ localStorage.token = res.data.token /* Then send action to reducer */ dispatch({ type: "USER_LOGIN", payload: { user: res.data, }, }) }) .catch(err => { console.warn(err) })}If you're a security nut, you can be extra careful and store your token in a session cookie with an httpOnly flag. This will prevent XSS attacks and side channel (BREACH) attacks. That said, localStorage is more common and perfectly fine for our purposes.
Now within our 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 user so we don't run into errors later when we assign these values to DOM elements via props and also destructure our payload for easier reading.
...function user(state = { email: "", username: "", id: ""}, action) { switch (action.type) { case "USER_NEW": return Object.assign({}, state, { email: action.payload.user.email, username: action.payload.user.username, id: action.payload.user.id }) case "USER_LOGIN": return Object.assign({}, state, { email: action.payload.user.email, username: action.payload.user.username, id: action.payload.user.id }) default: return state }}...Let's also update our userNew function to handle the response from our server.
...Actions.userNew = function userNew(user) { return dispatch => 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) => { /* If success, log the user in */ localStorage.token = res.data.token /* Then send action to reducer */ dispatch({ type: "USER_NEW", payload: { user: res.data } }) }) .catch((err) => { console.warn(err) })}...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 Login component to send the request via redux--we just previously hadn't sent the http request.
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.
What's more, if you check localStorage.token in your browser console, you'll see your current, valid JSON web token that we will later use for authentication.
Since login is working with Redux, we should change our Signup to use the Redux action as well. First import connect and Actions from Redux, then we need to replace the fetch call with a dispatched Redux action and connect our component in our export.
import React from "react"import cssModules from "react-css-modules"import { connect } from "react-redux"import style from "./style.css"import Actions from "../../redux/actions"...export class Signup extends React.Component { constructor(props) { super(props) this.submit = this.submit.bind(this) } submit() { const user = { username: document.getElementById("signup-username").value, email: document.getElementById("signup-email").value, password: document.getElementById("signup-password").value } this.props.dispatch(Actions.userNew(user)) } ...}export default connect()(cssModules(Signup, style))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.
> Fetch complete: POST "http://localhost:4000/api/users".> Object {data: Object}Now is a good time to refactor our 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.
...export class Home extends React.Component { constructor(props) { super(props) this.state = { formState: "login" } this.setFormState = this.setFormState.bind(this) } setFormState(formState) { this.setState({ formState }) }...}Then let's create a function that determines the content below our form that when clicked will change the state of our form.
...export class Home extends React.Component { constructor(props) { super(props) this.state = { formState: "login" } this.setFormState = this.setFormState.bind(this) } ... renderToggleContent() { switch (this.state.formState) { case "login": return ( <div className={style.changeLink} onClick={() => this.setFormState("signup")}> Need an account? Signup. </div> ) case "signup": return ( <div className={style.changeLink} onClick={() => this.setFormState("login")}> Have an account? Login. </div> ) default: return null } } render() { return ( <div className={style.leader}> <h1 className={style.title}>Phoenix Chat</h1> { this.state.formState === "signup" ? <Signup /> : null } { this.state.formState === "login" ? <Login /> : null } { this.renderToggleContent() } <img role="presentation" className={style.circles} src="/learnphoenix-static-assets/images/circles-full.png" /> </div> ) }}One thing that you will often see in React code is the use of 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 this. So for example, the two onClick functions below are the same:
// ES2015, and what we will useonClick={() => this.setFormState("login")}>// ES5onClick={this.setFormState.bind(this, "login")}Also note that if you need access to the event, you will need to pass it as a parameter if you use ES2015 syntax.
// ES2015 syntax, passing event as second parameteronClick={e => this.setFormState("login", e)}And now, when you click on the link, it toggles the form. Granted, it's not styled, but we can do that later.
Previous: Login and Authentication: Part 2Next: Check Login Status