RFR Section 5 – Connecting the Front-End and Back-End


Updated Mar 14th, 2022

Table of Contents

Course Summary

Chapter Details

Chapter 26. Quick Note About Debugging

In the following lesson we setup a catch block that should run if our request to register a user fails for any reason. However, we don’t have it output any actually useful information that will help you debug your issue. I’ve just adjusted our backend-api (May 9th 2020, make sure you have the latest controllers/userController.js from GitHub in your backend, to actually send the specific reasons why your request failed (for example, your password wasn’t long enough, your email is not a valid format, your username uses non-alphanumeric characters, etc…).

Reference the code in the note to finalize.

Chapter 27. Sending a Request From the Front-End

Make sure both front-end and back-end are running in two separate VS Code windows.

When the form is submitted we send to back-end which handles the storing in the database.

In “HomeGuest.js” add an onSubmit with a handleSubmit. In the “handleSubmit” function prevent the default with “e.preventDefault” and then send http request with axios instead of fetch,

Install axios and import so we can use leverage.

import Axios from "axios"

Axios.post('http://localhost:8080/register', {
  username: 'test',
  email: 'test@test.com',
  password: 'qwertyqwerty'

But implement error handling with try/catch and make sure you pass catch error to make Edge browser happy

The request is an “async” action so let’s use await and then make “handleSubmit” an “async” function

Open up the console before submitting so you can see any responses from the server. Also check the database that a new user was registered.

Chapter 28. Access Form Field Values with React

Create three pieces of state with useState.

import {useState} from "react"

const [username, setUsername] = useState()
const [email, setEmail] = useState()
const [password, setPassword] = useState()

Add on change evetn listernersto the form inputs. We can create a named function above or we can create an anonymous arrow function that runs {e => e.target.value}

Update the Axios request for our new state valueand take advantage of shorthand username: username becoming just “username”

Skipping client-side validation for now.

Chapter 29. Logging In

Want to see different header depending on if you are logged in or not.

First step is to find the sign-in form in the JSX and in the “Header.js” file cut the form element into the clipboard and add a temporary x placeholder.

Create a new “headerLoggedOut.js” file and paste in the clipboard.

In “Header.js” file import in this new file.

In HeaderLoggedOut bring in useState for username and paswsword and add onChenge event handlers for the input elements the same we did in the previous chapter. ON the openign form tag add an onsubmit that oints to handleSubmit. This function shoud prevent defaula ans use Axios to send reauest.

Set up a try/catch block with an e parameter for the catch.

IN the try block:

// inside async handleSubmit

const response = await Axios.post('http://localhost:8080/login', {username password})

Submit an invalid attempt on purpose and check console. Login with the correct values and check the console.

Use conditional code to render custom

if (response.data) {
} else {

Chapter 30. Render Different Components Depending on State

“Header.js” file and create new “HeaderLoggedIn.js” file and for the JSx it shudk retunr grab from index-feed.html file and grab “flex-row” div.

Do a find and replace for class to className

IN header.js import and use new file. Bring in useState to store whether user is logged in our

  {loggedIn ? < HeaderLoggedIn /> : <HeaderLoggedOut />}

Pass SetLoggedIn as a prop. IN HeaderLoggedOiut receive props and in the if block have props.setLOggedIn to true.

Ste thing up to have clicking sign out button update the state. IN header.js

In “headerLoggedIn.js” file receive props and to the button add an “onClick” event handler and set to an arrow function that triggers “props.setLoggedIn(false).”

Chapter 31. Persisting State (Local Storage)

One huge flaw is that if there’s a page reload we lose our state so we need to persist the data with the browser’s local storage feature.

In “HeaderLoggedOut.js” file

if (response.data) {
  localStorage.setItem('complexAppToken', response.data.token)
  localStorage.setItem('complexAppToken', response.data.token)
  localStorage.setItem('complexAppToken', response.data.token)

Check the application tab and storage and cookies to see the thing. No matter how many time we refresh the token is still there. Now we set up our app to set the iitial useState value to use the local storage


function handleLogout to remove properties from local storage using removeItem method.

Use piece of local storage to use your photo for your avatar by adjusting “src” attribute in “HeaderLoggedIn.js” file.

Chapter 32. Conditional Homepage Content

Visit base and you log in you should see different content.

Create a new “Home.js” file and copy/paste from course repo from the “home-index-feed.html” file the “h2” and “p” element.

In “Main.js” import Home and conditionally show with a conditional using ternary operator.

One of the most challenging aspects of React is managing state throughout your application. So we move or “lift” the state up the component tree and then pass dowm.

Cut state from “Header.js” to “Main.js” file and paste in just under component function.

Pass Header props of loggedIn and setLoggedIn

in Header.js file include props ot recive props and in the ternary add “props.” to before loggedIN and setLoggedIn.

in Main.js in the router lets have

{loggedIN ? <Home /> : <HomeGuest />}

Go to “Home.js” and make sure name is not hard-coded but pulling in dynamically

Passing down state is not the best way of doing things. We used to use redux and now we use context and useReducer instead of 3rd party. So we will refactor this state later in the course but you should know how to handle this way,

Chapter 33. Create Post Screen

Once you have logged in you will see create post button so we need to create a new “CReatPost.js” file and for the JSX copy from the “cerate-post.html” file and grab the form component and paste in between “Page” compoent tags.

Adjust “Main.js” so our router knows what to do.

In the “HeaderLoggedIn” bring in Link.

Update autofocus to be autoFocus and do the same for autoComplete and htmlFor.

In “CreatePost.js” import Axios from Axios” to send request in try/catch block.

const result = await Axios.post()

Chapter 34. View Single Post Screen

Create a “ViewSinglePost.js” file and for the JSX grab from single-post.html the div of d-flex to the div with a class “body-content.”

Update the necessary attributes.

Want to be able to visit at domain/post/postabc123

How do we redirect to push new url

Work with react router’s history using a tool called WithRputer from “react-router-dom”

In “CreatePost.js” use “props.history.push()”

Server sends back “id” of post as response. and we so we can make this dyncami with backticks and ${response.data}

Address bar should show 24 character string (generated by MongoDb Atlas).

Chapter 35. Flash Messages

For success message for 3-5 success message and then animated out. Where should this html live?

Animations handled by CSS and not React

Create a “FlashMessages.js” file, import into “Main.js” file, render in JSX, and set up some state

return (
    <div className="floating-alerts">
      {props.messages.map((msg, index) => {
        return (
        <div key={index} className="alert alert-success">{msg}</div>

Create a function named “addFlashMessages”

Pass this function into the “CreatePost” component tag in the JSX area.

<CreatePost addFlashMessage={addFlashMessage} />

In “CreatePost.js” receive the props and in the JSX use to trigger a flash message

props.addFlashMessage('Congrats, you successfully created a new post.')

Want o add a flash message from every componet and not just the “CreatePost” component and we don’t want to manually add props like this.