RoadToWebDev Day#12 — Building UI and connecting it to Backend

This is a part of my ongoing series about exploring the Road To Web Development, you can find the rest of the blogs here

This article is about creating the frontend of the sample application discussed in the previous articles(A simple application that stores the Song data entered by the user using the POST method and displaying the same using the GET method.), and also the API calls to connect the frontend with the backend that will result into a fully functioning application.

To get started with the react app, go through the given link.

As I have used React Hooks in the code, let me first give a brief introduction to that.

The hook is a new feature to the react. It allows you to use state and other React features inside the functional component rather than in a class component. React Hooks do not work inside the class. It does not anything like lifecycle methods instead, other simple methods are used. With the help of React Hooks, sharing stateful logic between components becomes easier.

Let us start with the main page.

React Router is used to navigate between the components, as it allows to change the browser URL. Its main components are:

  • BrowserRouter: It is used to keep the UI synchronized with the URL. Other router components are kept inside this component.
  • Switch: Switch component is used to render only the first route that matches the location rather than rendering all matching routes.
  • Route: It is a conditional router component that matches its path with the current URL, and if true, it results in the corresponding component.

Every component used in a file has to be imported as

import ComponentName from "...path..";

Navigation Bar:

The fourth React Router component is used here, and that is

  • Link: It is used to create links to different routes and implement navigation around the application.

Here the path in the <Link> has to be the same as in the <Route> in order to get correct results. The syntax is:

<Link to="path">...</Link>

Now we will get to the code that will show us the list of songs from the database. The API calls are included in the code itself.

In class components, we were using setState() methods to handle the state but here with react hooks, useState() is used.

useState() method accepts argument(i.e. Initial value of the state)and returns a pair of values: the current value of the state and a function that will update the state.

React Fragment helps in returning multiple elements just like <div>.

Now we have the data in the form of state ‘song’. To display it to the DOM, we need to use the map() function and return JSX from the callback function. This is the most common use case of the map() function in React.

Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity:

GET API Call:

The useEffect() method does the job of three life cycle methods componentDidMount(), componentDidUpdate(), and componentWillUnmount().

That means it is a function that can function before rendering, after rendering, and before the component is unmounted. In simple terms, useEffect() will be called every time something affects your component.

useEffect(() => { 
// some component logic to execute...
}, []);

Here we have used it as above. In the second argument, [state,setState] can be passed on if we want to make useEffect() method dependent. But here we have kept it as an empty array.

Axios Library: It is a library that helps us make HTTP requests. It will make the frontend connected to the backend.

At first, axios.get(“ URL”) let the react know where to take information from. “.then( )” takes in the response and sets the state (here: song) by the method that handles the state(here: setSong( )). And lastly “.catch( )” catches error if any occurs.

The job of this certain API is to fetch the data from the backend and show it to the frontend.

Displaying the song list

Taking inputs from the user:

First of all, the input states are initialized to null in the useState() function.

Here, in some functions, the following line of code is seen.

const values= [...inputFields]

These three dots(…) is known as the Spread operator. The Spread operator allows expanding an iterable like a string, object, or array into its elements. It is majorly used when more than one values are to be copied into a variable. Here we are copying all the values of inputFields into a const variable ‘value’.

Now if you look at the form, every input tag has the onChange event which will call an arrow function ‘handleInputChange’ after every change in input.

handleInputChange(): It takes in two arguments that are index and event and the correct input value will be fetched from ‘event’ and will be stored at its ‘index’. An if..else ladder is applied here that will compare the input variable name with the help of ‘event.target.name’ and will store the value in the array value at its ‘index’ fetched from ‘event.target.value’. And finally, the function ‘setInputField’ is called that will update the state values.

As the form had to be dynamic here, in order to pass a single song or a list of songs at a time, two buttons are added to add and delete the input fields.

handleAddFields(): Here, ‘.push()’ function is used to add another row of empty inputfields into the array ‘values’.

handleRemoveFields(): Here an argument ‘index’ is passed from the form in order to delete the row of input fields from the correct position and that can be done with the help of ‘.splice’ function.

array.splice(index, number_of_elemenets_to_be_removed);

handleSubmit() function will do its job after the user clicks the save button.

In normal circumstances, events like onSubmit refresh the web page. To avoid this, event.preventDefault() can be used. This method will prevent the default behaviour of form submission and will display the user’s input data even after clicking the submit button.

POST API call:

The syntax of axios.post( ) is quite similar to that of axios.get( ).

This method requires two parameters. First, it needs the URL(Where to send the data), and the second one, the data(here: The state ‘inputFields’).

This API will deliver the data to the backend for further operations.

Taking in the inputs

As we have completed the code, let us go to http://localhost:3000/ and check the output.

Add the song/s details. On saving this list, the backend will call the POST request that will append the data into the database.

Checking if everything works fine.

References:

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store