DEV Community

Pedro Alarcon
Pedro Alarcon

Posted on

React- Flask Communication

Introduction

In modern web development, applications are often divided into two main parts: the frontend and the backend. Understanding how these two components communicate is crucial for creating dynamic and interactive web applications. Today we will talk about the Frontend Using React and the Backend using Flask.
For a web application to function, the frontend and backend must communicate effectively.


Frontend

The frontend, also known as the client-side, is the part of a web application that users interact with directly. It includes everything that users experience in their web browser, such as:

  • User Interface (UI) : The layout, buttons, forms, and other visual elements.

  • Client-Side Logic : Code that runs in the browser, typically written in JavaScript, along with libraries or frameworks like React

  • Styling : CSS and frameworks like Bootstrap that ensure the application looks good across different devices and screen sizes.


Backend

The backend, or server-side, is the part of the application that runs on the server. It is responsible for:

  • Database Management : Storing, retrieving, and updating data.

  • Business Logic : The rules and operations that define how data can be manipulated and transformed.

  • Server Configuration : Handling server setup, routing, and ensuring the application runs smoothly.


Setting up Backend using SQLite

Creating Model- Table

Let's start off by creating a model Called Animal and then create the tablename animals. We will create some columns and give them certain attributes like id (Integer), name (String), species (String) and age (Integer).

Model Setup

  • id: This is the primary key of the table. It's an integer that uniquely identifies each row.

  • name: This is a string column with a maximum length of 100 characters. The nullable=False argument means that this field cannot be null.

  • species: Similar to name, this is a string column with a maximum length of 100 characters and cannot be null.

  • age: This is an integer column that cannot be null.

  • repr Method: This method defines how the Animal object is represented as a string, which is useful for debugging. When you print an Animal object, it will display its id, name, species, and age in a readable format.

After running

  • flask db init
  • flask db migrate -m "initial migration"
  • flask db upgrade head

It should appear in database and now we can focus on the backend route and work on the CRUD sequences. Lets say for example we already seeded the database and our tables are now filled.

Animal-DataBase

Creating Backend route

Here we Set up the backend route in a file called app.py.

 Backend-route

  • AnimalList handles GET and POST requests for listing and creating animals

  • GET method retrieves all animals and returns them as JSON.

  • POST method creates a new animal based on JSON data and returns the created animal as JSON.

Api Setup

The AnimalList resource is added to the Flask-RESTful API at the endpoint /animals. This setup provides a basic yet functional CRUD API for managing animals, suitable for integration into a larger Flask application. Adjustments can be made based on specific project requirements and additional features can be added as needed.


Setting up Frontend using react

Create a file

Now that we have setup the Backend when we move to the client side, we use a React component to fetch and display the data. The component will make an HTTP GET request to the /animals endpoint when it mounts.

Frontend-Setup-pt1

  • The useEffect hook is used to perform side effects, in this case, fetching data from the backend. The empty dependency array ([]) ensures that this effect runs only once when the component mounts.
  1. Component Initialization :
  • When the AnimalList component is first rendered, it initializes its state using the useState hook. The animals state will hold the fetched data, loading indicates if the data is being fetched, and error will store any errors that occur during the fetch.
  1. Effect Hook to Fetch Data :
  • The useEffect hook is used to perform side effects, in this case, fetching data from the backend. The empty dependency array ([]) ensures that this effect runs only once when the component mounts.
  1. Fetching Data :
  • The fetch('/animals') function sends a GET request to the /animals endpoint of the backend.

  • The then(response => {...}) block checks if the response is okay (status code 200-299). If not, it throws an error.

  • If the response is okay, it converts the response body to JSON using response.json().

  • The second then(data => {...}) block takes the parsed JSON data (the list of animals) and updates the animals state. It also sets loading to false since the data has been successfully fetched.

  1. Error Handling :
  • If any error occurs during the fetch operation, the catch(error => {...}) block catches the error, updates the error state with the error message, and sets loading to false.

Frontend-Setup-pt2

  1. Rendering the Component :

While the data is being fetched (loading is true), a loading message is displayed.

If an error occurs (error is not null), an error message is displayed.

If the data is successfully fetched (loading is false and error is null), the component maps over the animals array and renders a list of animals.


Summary

We demonstrated how to connect a Flask backend with a React frontend for managing a list of animals. We started by setting up the Flask backend, defining a simple Animal model with SQLAlchemy, and creating RESTful API endpoints to retrieve and add animals. On the frontend, we developed a React component that fetches and displays the list of animals from the backend. Using the useEffect hook, the component makes an HTTP GET request to the "/animals" endpoint, processing the response, and updates the component's state with the fetched data while managing loading and error states. This setup allows for seamless communication between the backend and frontend, providing a robust and interactive user experience for managing animal data.

Resources

Top comments (0)