React Demos — Episode2 — Ajax Data Loading

Jawadhasan
4 min readJan 22, 2023
Photo by Daniel K Cheung on Unsplash

Introduction

This is the second post in this series of React Demos. You can check the previous post on this link.

Making Ajax calls and performing CRUD operations are very common in web development. In this post we’ll load data from public APIs and display it in react components.

Show Bitcoin Price

We’ll start with a simple demo and perform a GET request to read the data from Coindesk’s public API

Here is the component

Notice the useState hook for state.

  • useState Hook will allow the use of state in function component without writing a separate class component.
  • useEffect Hook, will allow to perform side effect operations such as fetching data, clean up, or DOM manipulation.

We can now use this component in Misc page, which we setup in the previous post

and here is the component’s view

No data yet, so lets do this next.

Making Ajax Call

To make ajax calls, we can use browser’s fetch API along with useEffect hook as shown below:

useEffect() takes a function as first argument. This function will execute after the first render and after every component update. So this function is an apt place to call the data API.

Passing a second argument to useEffect is optional. Passing an empty array [] ensures this effect will run just once; otherwise, it will run after every render.

--

--

Jawadhasan

Software Solutions Team Lead | Cloud Architect | Solutions Architect