Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Full-Stack Flask and React

You're reading from  Full-Stack Flask and React

Product type Book
Published in Oct 2023
Publisher Packt
ISBN-13 9781803248448
Pages 408 pages
Edition 1st Edition
Author (1):
Olatunde Adedeji Olatunde Adedeji
Profile icon Olatunde Adedeji

Table of Contents (21) Chapters

Preface 1. Part 1 – Frontend Development with React
2. Chapter 1: Getting Full Stack Ready with React and Flask 3. Chapter 2: Getting Started with React 4. Chapter 3: Managing State with React Hooks 5. Chapter 4: Fetching Data with React APIs 6. Chapter 5: JSX and Displaying Lists in React 7. Chapter 6: Working with React Router and Forms 8. Chapter 7: React Unit Testing 9. Part 2 – Backend Development with Flask
10. Chapter 8: SQL and Data Modeling 11. Chapter 9: API Development and Documentation 12. Chapter 10: Integrating the React Frontend with the Flask Backend 13. Chapter 11: Fetching and Displaying Data in a React-Flask Application 14. Chapter 12: Authentication and Authorization 15. Chapter 13: Error Handling 16. Chapter 14: Modular Architecture – Harnessing the Power of Blueprints 17. Chapter 15: Flask Unit Testing 18. Chapter 16: Containerization and Flask Application Deployment 19. Index 20. Other Books You May Enjoy

Fetching Data with React APIs

Over the past few years, there has been an increase in the demand for database-driven web applications. This increase is a consequence of the abundance of data available at this present time. With widespread internet adoption, businesses leverage web applications to interact with customers, employees, and other stakeholders.

More than ever, web developers are constantly faced with tasks such as the organization and consumption of data. Both internal and external data require us to have smart and business-oriented database-driven web applications.

As a full stack software engineer, some of your frontend tasks will be to consume data, either from an internally developed API or a third-party API. Before we delve into approaches or tools you can use to fetch data in React projects, let’s briefly discuss what APIs are all about and why they are redefining ways of building user interfaces and web applications.

An API simply allows communication...

Technical requirements

The complete code for this chapter is available on GitHub at: https://github.com/PacktPublishing/Full-Stack-Flask-and-React/tree/main/Chapter04.

Fetching data using the Fetch API in React

Fetch API is an inbuilt API in a web browser that provides the JavaScript interface for communication over the internet using HTTP. Every web browser has a JavaScript engine as a runtime to compile and run JavaScript code.

The React ecosystem relies inarguably on JavaScript. This is a fact and one of the reasons you are expected to understand modern JavaScript before delving into React application development.

As a React developer, you will need network resources to build web applications. The fetch() method provides you with the means to access and manipulate HTTP object requests and HTTP protocol responses. Let’s say that in our web application, we want to display the list of conference speakers and their associated data. This information is housed in another resource database server.

From a third-party public API, we are going to consume the user’s resource to fetch hypothetical data to be used in our React application...

Fetching data using async/await syntax

There are three ways to write asynchronous codes in vanilla JavaScript: callbacks, promises, and async/await. In this section, we are going to focus on async /await and see how it can be used in React web applications. async/await is an improvement on promises.

The following snippet explains how async/await can be used to fetch data from an API using a promise-based approach:

import React, { useEffect, useState } from 'react';const App = () => {
    const [data, setData] = useState([]);
    const API_URL = "https://dummyjson.com/users";
    const fetchSpeakers = async () => {
        try {
            const response = await fetch(API_URL);
            const data = await response.json();
  ...

Fetching data using Axios

Axios is simply a lightweight JavaScript, promise-based HTTP client used to consume API services. It is mainly used in the browser and Node.js. To use Axios in our project, open the project terminal and type the following:

npm install axios

Now, let’s see how to use Axios in the following code snippet:

import React, { useEffect, useState } from 'react';import axios from 'axios';
const App = () => {
    const [data, setData] = useState([]);
    const getSpeakers = ()=>{
        axios.get(
            "https://jsonplaceholder.typicode.com/users")
            .then(response => {
                setData(response.data)
  ...

Fetching data using the React Query in React

React Query is an npm package library created for data fetching purposes with a ton of functionalities loaded with it. In React Query, the state management, pre-fetching of data, request retries, and caching are handled out of the box. React Query is a critical component of the React ecosystem with over a million downloads weekly.

Let’s refactor the code snippet we used in the Fetching data using Axios section and experience the awesomeness of React Query:

  1. First, install React Query. In the root directory of the project, do the following:
    npm install react-query
  2. Inside App.js, add the following:
    import {useQuery} from 'react-query'import axios from 'axios';function App() {  const{data, isLoading, error} = useQuery(    "speakers",    ()=>{ axios(      "https://jsonplaceholder.typicode.com/users")&...

Summary

Handling data is a critical component of any web application. React has proven to be very efficient and scalable in handling data at scale. In this chapter, we discussed various approaches you can utilize in your project to handle data fetching. We discussed fetching data using the Fetch API, async/await, Axios, and React Query.

In the next chapter, we are going to discuss JSX and how you can display lists in React.

lock icon The rest of the chapter is locked
You have been reading a chapter from
Full-Stack Flask and React
Published in: Oct 2023 Publisher: Packt ISBN-13: 9781803248448
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime}