Reader small image

You're reading from  Full-Stack Flask and React

Product typeBook
Published inOct 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781803248448
Edition1st Edition
Right arrow
Author (1)
Olatunde Adedeji
Olatunde Adedeji
author image
Olatunde Adedeji

Olatunde Adedeji is a seasoned web developer with over 15 years of experience in developing dynamic and detail-oriented enterprise web applications. Along with his extensive experience in developing, maintaining and supporting mobile, web and enterprise applications in Python, Go and JavaScript, Olatunde has consistently delivered excellent services, as team lead, team member or in consultancy capacity. Olatunde is proficient in application design and solution blueprinting; including mastery of application development tools such as: Flask, Django, Gin, React, and NodeJS. When not weaving the web and playing chess, Olatunde spends time with his wife, Adedoyin and two daughters, Mitchelle and Mabel.
Read more about Olatunde Adedeji

Right arrow

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 2023Publisher: PacktISBN-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.
undefined
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

Author (1)

author image
Olatunde Adedeji

Olatunde Adedeji is a seasoned web developer with over 15 years of experience in developing dynamic and detail-oriented enterprise web applications. Along with his extensive experience in developing, maintaining and supporting mobile, web and enterprise applications in Python, Go and JavaScript, Olatunde has consistently delivered excellent services, as team lead, team member or in consultancy capacity. Olatunde is proficient in application design and solution blueprinting; including mastery of application development tools such as: Flask, Django, Gin, React, and NodeJS. When not weaving the web and playing chess, Olatunde spends time with his wife, Adedoyin and two daughters, Mitchelle and Mabel.
Read more about Olatunde Adedeji