APIs with REACT | + components / state / jsx
It’s got it all! *

React - Using API DataCall Web Apis with UseEffect Hookmore -
REACT - USING API DATA
  • https://www.digitalocean.com/community/tutorial_series/how-to-code-in-javascript
  • https://www.digitalocean.com/community/tutorials/how-to-use-the-javascript-fetch-api-to-get-data
  • https://www.digitalocean.com/community/tutorials/how-to-call-web-apis-with-the-useeffect-hook-in-react
  • https://www.digitalocean.com/community/tutorials/how-to-manage-state-on-react-class-component

https://medium.com/@dtkatz/10-react-starter-project-ideas-to-get-you-coding-5b35782e1831
https://rapidapi.com/blog/how-to-use-an-api-with-react/

https://medium.com/@dtkatz/10-react-starter-project-ideas-to-get-you-coding-5b35782e1831

https://rapidapi.com/blog/how-to-use-an-api-with-react/

How To Use an API with ReactJS

By Jarrett Retz // July 13, 2021

Table of Contents [show]

Intro

A client recently asked me, “Do you know how to use APIs?”.

Frankly, I hesitated when answering because I thought,

“What do you mean by API?”.

There wasn’t enough context for me to figure out what kind of Application Programming Interface (API) she was talking about, and you can learn more about the various types of APIs here.

Consider this, my favorite definition from the article linked above concerning different types of APIs is;

…an API provides interactions between one software and another, but not users.

Given a broad definition, asking a developer if they know how to use APIs is like asking a chef if they know to use the stove.

On rare occasions, they may not.

However, truthfully it depends on the type of stove and what they are using it for.

If you grant me the comparison: using an API depends on the API and what I am using it for.

Browse the Best Free APIs List

Web APIs

RapidAPI is a platform for accessing web-based APIs.

The most popular type of web API is a Representational state transfer API or RESTful API for short. To be brief, it follows an architecture that uses predefined and stateless operations to access web resources.

Using web APIs requires the use of HTTP requests. Different types of requests include GET, POST, DELETE, PATCH, etc. If you have written some code and it needs to communicate with code somewhere else, it will send an HTTP request over the internet. Next, let’s discuss the HTTP request types just mentioned. You will notice that the types are matched to verbs that are similar to their function:

  • GET: Used to request data from an endpoint
  • POST: Sends data to an endpoint
  • DELETE: Remove data from an endpoint.
  • PATCH: Update a record or data value at an endpoint.

These types of interactions are external from the local environment, and therefore, the APIs that are providing the data or services are called external APIs. It is difficult to fathom how useful it is to have the capability to access external APIs for various data and services.

API Keys

As previously mentioned, external APIs offer data, services, or both. Having access to the API can be valuable, therefore, you may need to buy a subscription to use it. Don’t worry, there are still plenty of free APIs.

Furthermore, the hypothetical external API does not have unlimited resources, so letting software call the API an unlimited amount of times at no cost could render it useless. Consequently, API providers will issue secret API-keys to monitor usage over time. Using RapidAPI allows the developer to only deal with one key (RapidAPI’s key), otherwise, developers would need to have API-keys for all of their APIs. Most of the time API-keys need to be kept secret, however, some services will issue public API keys.

Soon we will learn how to use the RapidAPI dashboard to simplify our understanding of how these parts work together, but first, let’s talk about React!

What is React?

A JavaScript library for building user interfaces

ReactJS.org

The ReactJS library is useful for handling the relationship between views, state, and changes in state.

Views are what the user sees rendered in the browser. State refers to the data stored by different views that typically rely on who the user is, or what the user is doing. For example, when you sign into a website it may show your user profile (view) with your name (state).

The state data may change user-to-user but the view remains the same. Expanding on our example, let’s suppose the website is an e-commerce site. If you are signed in, the website may have a Products You Might Like section. However, if you are not signed in, rendering that view may not make sense. ReactJS helps developers manage that kind of scenario with ease.

The sections below will be a brief introduction to ReactJS. For a more comprehensive tutorial, you can visit the ReactJS.org tutorial page.

Components

Views are created inside of components. There two types of components: class and function. Below is a class component:

class ExampleComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { };
  }
  render() {
    return (
      <div>
        <h2>This is a view created by a class component</h2>
      </div>
    );
  }
}

 

Notice that we declare a state object in the constructor. This where we can store data to be used inside the view. Speaking of the view, it is rendered to the page inside of render().

A function component may look like:

const ExampleComponent = (props) => {
    const [stateVariable, setStateVariable] = useState('');
    return (
        <div>
            <h2>This is a function component view</h2>
        </div>
    )
}

 

Unlike the class component, our function returns the view and does not need a render function. Also, the state is controlled by the React hook function useState.

Later on, we will use class components in the example app.

Props

We can pass data or functions down into components through props. Here’s an example:

import React, { useState } from 'react' 
import ReactDOM from 'react-dom' 
const ParentComponent = () => { 
    const [stateVariable, setStateVariable] = useState('this is the starting value for the variable'); 
    return ( 
        <div> 
            <h2>This is a function component view</h2>
            <ChildComponent exampleProp={stateVariable} />
        </div> 
    ) 
} 
const ChildComponent = (props) => {
    return (
        <div>
            <h3>{props.exampleProp}</h3>
        </div>
    )
}
ReactDOM.render( <ParentComponent />, document.getElementById('app') );

 

 

In the above example, the string 'this is the starting value for the variable' is rendered to the page in replace of {props.exampleProp}.

The child component is rendered inside of the parent component and can inherit data passed down to through properties.

This a confusing concept at first because it does not read procedurally, but it will make more sense when we start using actual data. It’s a big reason why React can be so powerful.

JSX

JSX looks like an HTML templating language but is more powerful. We already saw how JSX can embed data into a view using curly brackets during our previous example. It looks very similar to HTML but has many differences. A few are:

  • passing custom props as attributes on an element tag
  • Instead of assigning CSS classes with class=, JSX uses className=. Camel casing is used for event listeners as well (I.e onClick, onHover).
  • closing tags are different depending on the elements. Below are a few examples.

HTML input and image tags:

<img class="" src="" alt="" >
<input type="text" required>

JSX input, and image tags:

<img className="" src="" alt="" />
<input type="text" required />

In addition to the above subtle changes, JSX tags can be self-closing. A valid JSX element could be.

You can learn more about JSX on React’s documentation page.

Side Effects

Side effects occur when a function goes outside of its scope or it is affected by something outside of the function body. Making an HTTP request and saving the result to the components state is a side effect.

Lifecycle Methods

In React, components have methods that are executed during the different phases of the components. These methods are called lifecycle methods.

It takes practice to figure out where and how certain lifecycle methods should be used. Regardless, the most important for HTTP requests is componentDidMount with class components and useEffect with functional components.

Grabbing the examples above, let’s add the methods we are talking about to the components.

Class component:

**

import React from 'react'
import ReactDOM from 'react' 
class ExampleComponent extends React.Component { 
    constructor(props) { 
        super(props); 
        this.state = { }; 
    } 
    componentDidMount() {
        // send HTTP request
        // save it to the state
    }
    render() { 
        return ( 
            <div> 
                <h2>This is a view created by a class component</h2> 
            </div> 
        ); 
    } 
} 
ReactDOM.render( <ExampleComponent />, document.getElementById('app') );

 

Function component:

import React, { useState, useEffect } from 'react' 
import ReactDOM from 'react-dom' 
const ExampleComponent = (props) => { 
    const [stateVariable, setStateVariable] = useState('');
    useEffect(() => {
        // send HTTP request
        // save response to variable
    }, [])
    return ( 
        <div> 
            <h2>This is a function component view</h2> 
        </div> 
    ) 
} 
ReactDOM.render( <ExampleComponent />, document.getElementById('app') );

 

These methods are used because they are called immediately after the component is mounted to the DOM (Document Object Model).

Here an example of how this works:

  1. User visits webpage
  2. The component is mounted to the DOM (webpage)
  3. The componentDidMount or useEffect method is called sending off the HTTP request
  4. The webpage gives an indication it is loading data
  5. The data is received from the external API and added to state (side effect)
  6. The component renders with the data that was fetched.

That was a bit of a crash course, and I do not expect you to have a full understanding of React. However, in this circumstance, the best way to learn is to build it! Therefore, let’s get started!

Prerequisites

Let’s make sure that you are fully prepared to advance and build out API calls using ReactJS. Below are a few prerequisites:

  • RapidAPI account. It’s free to sign-up and the API we use in the example below is free as well!
  • An internet connection and a browser that isn’t Internet Explorer. IE has some compatibility issues that can be easily avoided. I recommend Firefox or Google Chrome.
  • A reputable text editor. I use Visual Studio Code, however, another popular example is Sublime Text.
  • A general understanding of HTML, CSS, and Javascript.
  • Knowledge of how to use the command-line on your operating system. The commands are simple and should be similar across systems, however, there might be a slight variation. Looking up the appropriate command should be quick and easy.
  • NodeJS and NPM installed locally. There are installation instructions on NodeJS.org.

NPM stands for Node Package Manager. Unsurprisingly, it is the package manager for ReactJS and NodeJS packages. We will use it to download React and other dependencies.

How to Fetch/Call an API with React

View Repository on Github

In this example, we will learn how to send HTTP requests to a database to get, create, update and delete external data using an API on RapidAPI with React. Then, we will learn how to display this data on the webpage. Finally, I will point you towards more advanced examples so you can continue to grow!

1. Create a Basic Project Structure

Make a new folder. I named mine react-api-call.

Open up your text editor inside of the new folder and navigate into the new folder with your terminal.

Create the following folders:

  • public
  • src

Inside public create the file index.html and add the following code to it.

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Call Api</title>
    <!-- Load bootstrap -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body>
    <div id="App"></div>
  <!-- from https://reactjs.org/docs/add-react-to-a-website.html -->
  <!-- Load React. -->
  <!-- Note: when deploying, replace "development.js" with "production.min.js". -->
  <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
  <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
  <!-- Load our React component. -->
  <script src="js/app.js"></script>
  <!-- Load bootstrap js and dependencies -->
  <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>

 

Call Api

There is not much going on in this HTML file. We created a container for the app with an id of ‘App’ and loaded in:

  • Bootstrap for styling
  • React and React-DOM in the body Javascript
  • React component (not created yet)

Next, inside of the public folder, create the folder js. This will be an empty folder.

After that, inside of src folder create the empty file app.js. Your project structure should look like

tree structure without node_module folder

The above picture does not include the node_modules folder that should be in the project root as well.

2. Add React Component

Back in the terminal run these two commands:

  1. npm init -y: Creates an npm package in our project root
  2. npm install babel-cli@6 babel-preset-react-app@3: Installs the packages we need to convert JSX to HTML

Because JSX isn’t compatible with vanilla Javascript & HTML there needs to be a way to compile it into something that is. We installed Babel packages above to handle the translation.

In src/app.js add the following code:

'use strict';
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      friends: [],
      name: '',
      id: '',
      notes: ''
    };
    this.create = this.create.bind(this);
    this.update = this.update.bind(this);
    this.delete = this.delete.bind(this);
    this.handleChange = this.handleChange.bind(this);
  }
  componentDidMount() {
    // get all entities - GET
  }
  create(e) {
    // add entity - POST
    e.preventDefault();
  }
  update(e) {
    // update entity - PUT
    e.preventDefault();
  }
  delete(e) {
    // delete entity - DELETE
    e.preventDefault();
  }
  handleChange(changeObject) {
    this.setState(changeObject)
  }
  render() {
    return (
        <div className="container">
          <div className="row justify-content-center">
            <div className="col-md-8">
              <h2 className="display-4 text-center">Make An API Call in React</h2>
              <form className="d-flex flex-column">
                <legend className="text-center">Add-Update-Delete Friend</legend>
                <label htmlFor="name">
                  Friend Name:
                  <input
                    name="name"
                    id="name"
                    type="text"
                    className="form-control"
                    value={this.state.name}
                    onChange={(e) => this.handleChange({ name: e.target.value })}
                    required
                    />
                </label>
                <label htmlFor="notes">
                  Friend notes:
                  <input
                    name="notes"
                    id="notes"
                    type="test"
                    className="form-control"
                    value={this.state.notes}
                    onChange={(e) => this.handleChange({ notes: e.target.value })}
                    required
                    />
                </label>
                <label htmlFor="id">
                  Friend ID:
                  <input
                    name="id"
                    id="id"
                    type="text"
                    className="form-control"
                    value={this.state.id}
                    onChange={(e) => this.handleChange({ id: e.target.value })}
                    />
                </label>
                <button className="btn btn-primary" type='button' onClick={(e) => this.create(e)}>
                  Add
                </button>
                <button className="btn btn-info" type='button' onClick={(e) => this.update(e)}>
                    Update
                </button>
                <button className="btn btn-danger" type='button' onClick={(e) => this.delete(e)}>
                    Delete
                </button>
              </form>
            </div>
          </div>
        </div>
    );
  }
}
let domContainer = document.querySelector('#App');
ReactDOM.render(<App />, domContainer);

 

 

Notice we have inserted empty functions to fill with APIs calls and bound them to the component in the constructor function. Also, we initialized our state and defined variables that we need to keep track of.

Taking a look at the JSX, you notice that we are using camel-case (camelCase) to define attributes and properties. Furthermore, we are controlling the inputs by assigning them to values in state and passing an onChange handler.

Next, we need to set up a live server to make the development process easier to understand.

If you are using VSCode you can download the plugin Live Server. This allows you to watch your changes update automatically.

If you are not using VSCode there is most likely an easy way to get the same functionality with your text editor with the help of your favorite search engine.

After installing the plugin in VSCode, select the ‘Go Live’ button which will start the application on a port locally (i.e http://localhost:5050). The browser gives you the option to select the directory to run the server in choose public.

Go Live

Although the site is live, nothing will display because we are not compiling our React code in the src directory.

In the terminal run:

npx babel --watch src --out-dir public/js --presets react-app/prod

The command will automatically compile the code in src and place it into the appropriately named folder in public/js.

The output in your terminal should be:

src/app.js -> public/js/app.js

Now, you should see our React file code appearing in the browser.

manke an api call in react form

3. Add API Calls

Our interaction with an API depends on that specific API. It may only offer certain types of HTTP methods, endpoints, and parameters. Whatever the case we need instructions on what that API expects our requests to look like. I have chosen to use the FaiRESTdb API for this example so I can demonstrate the four main types of API calls that we should know (GET, POST, PUT, DELETE).

Let’s explore the dashboard tool.

Open Up FaiRESTdb API on RapidAPI

Search for the API on the marketplace or follow the link to the API dashboard. In the dashboard you can find:

  • endpoint details
  • pricing
  • documentation
  • community discussions

 

fairestdb_documentation-768x332

The different types of endpoints that are available can be found on the left side of the interactive dashboard.

required parameters for add entity

Depending on which endpoint is selected, a definition and parameter information will be available in the center of the dashboard.

 

Finally, the right side of the dashboard builds code snippets based on the endpoint and the parameters that we enter. In this way, the dashboard works from left-to-right.

Javascript code snippet

In addition to ready-to-use code snippets, the right side of the dashboard displays sample response objects that are important to planning our application. Most APIs allow us to test endpoints and receive real response data right in the API dashboard.

Response objects consist of the data the API returns to our request. Response objects can be JSON, XML, audio/video etc. However, the API we are using will respond in a JSON format. JSON stands for Javascript Object Notation and is a lightweight data exchange framework.

We can create a database for our sample application in the dashboard after subscribing because the tests are real requests.

Click the blue ‘Subscribe to Test’ button on the dashboard.

subscribe to test button

The pricing panel shows us the available plans and quota restrictions for the API. Notice, we get 500 calls a month, then it’s $0.01 for each subsequent call. You may think that would be difficult to keep track of, however, RapidAPI has a developer dashboard that allows you to track your API calls!

basic subscription for faiRest api

Select the Basic plan.

Create Database

Now that we can use the API, head back to the dashboard and select the Create Database endpoint. Our example will need a database to communicate with and we can create one here in the dashboard.

Change the name value in the request to ‘friend’.

json object with a key of name and a value of friend

Hit the ‘Test Endpoint’ button. A response object should appear on the right side of the dashboard telling you that the database was created successfully!

response for success creation of database

Now that we have a database, we need to make a friend model. Instead of setting up another function, for the sake of simplicity, we will create a basic model with the dashboard.

Create a Model

Just like we did for the database, we need to select the endpoint, fill in the parameters, and send the request.

Select the Create Model endpoint and add the appropriate parameters.

friendModel schema with title, name, notes attributes

Select the Test Endpoint button. The response should be similar to:

successful response object

Great! Now it’s time to add the API code to our React component!

Grab Code Snippets

The process for retrieving the code snippets is as follows:

  1. Select the endpoint
  2. Change parameters and schema
  3. Select the desired language and library
  4. Copy the code

Let’s do this for the Add Entity (POST), Get All Entities (GET), Update Entity (PUT), and Delete Entity (DELETE) endpoints.

Remember, the database name is ‘friend’, the model name is ‘friendModel’, and the schema needs to match the friend model schema we set up.

For this example, I am using the (JavaScript) fetch library.

I’ve edited the snippets a little bit so they can receive JSON responses and send JSON requests. Furthermore, I made React specific changes to show how we are going to getting the variables from the component state for the request.

Here’s what the snippets should be for each endpoint (make sure you are substituting your RapidAPI key):

Add Entity:

// creates entity
fetch("https://fairestdb.p.rapidapi.com/friend/friendModel", {
  "method": "POST",
  "headers": {
    "x-rapidapi-host": "fairestdb.p.rapidapi.com",
    "x-rapidapi-key": "apikey",
    "content-type": "application/json",
    "accept": "application/json"
  },
  "body": JSON.stringify({
    name: this.state.name,
    notes: this.state.notes
  })
})
.then(response => response.json())
.then(response => {
  console.log(response)
})
.catch(err => {
  console.log(err);
});

 

Get All Entities:

// read all entities
fetch("https://fairestdb.p.rapidapi.com/friend/friendModel", {
  "method": "GET",
  "headers": {
    "x-rapidapi-host": "fairestdb.p.rapidapi.com",
    "x-rapidapi-key": "apikey"
  }
})
.then(response => response.json())
.then(response => {
  this.setState({
    friends: response
  })
})
.catch(err => { console.log(err); 
});

 

Update Entity:

// read all entities
fetch("https://fairestdb.p.rapidapi.com/friend/friendModel", {
  "method": "GET",
  "headers": {
    "x-rapidapi-host": "fairestdb.p.rapidapi.com",
    "x-rapidapi-key": "apikey"
  }
})
.then(response => response.json())
.then(response => {
  this.setState({
    friends: response
  })
})
.catch(err => { console.log(err); 
});

 

Delete Entity:

// deletes entities
fetch(`https://fairestdb.p.rapidapi.com/friend/friendModel/_id/${this.state.id}`, {
  "method": "DELETE",
  "headers": {
    "x-rapidapi-host": "fairestdb.p.rapidapi.com",
    "x-rapidapi-key": "apikey"
  }
})
.then(response => response.json())
.then(response => {
  console.log(response);
})
.catch(err => {
  console.log(err);
});

 

 

IMPORTANT: Comment out the componentDidMount function after the code is added. This will stop the Get All Entities function from firing every time we make and edit and the app rerenders.

Next, add the snippets to the application inside the appropriate function. We want the app to retrieve all the entities when the component loads, therefore, the Get All Entities snippet goes in the componentDidMount function.

Add Snippets to Functions

For the snippets to work, I have added the necessary state variables that the functions need.

After adding the snippets to their corresponding functions, and modifying JSX, src/app.js should look like:

 

'use strict';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      friends: [],
      name: '',
      id: '',
      notes: ''
    };

    this.create = this.create.bind(this);
    this.update = this.update.bind(this);
    this.delete = this.delete.bind(this);
    this.handleChange = this.handleChange.bind(this);
  }

//   componentDidMount() {
//     // get all entities - GET
//     fetch("https://fairestdb.p.rapidapi.com/friend/friendModel", {
//       "method": "GET",
//       "headers": {
//         "x-rapidapi-host": "fairestdb.p.rapidapi.com",
//         "x-rapidapi-key": API_KEY
//       }
//     })
//     .then(response => response.json())
//     .then(response => {
//       this.setState({
//         friends: response
//       })
//     })
//     .catch(err => { console.log(err); 
//     });
//   }

  create(e) {
    // add entity - POST
    e.preventDefault();

    // creates entity
    fetch("https://fairestdb.p.rapidapi.com/friend/friendModel", {
      "method": "POST",
      "headers": {
        "x-rapidapi-host": "fairestdb.p.rapidapi.com",
        "x-rapidapi-key": API_KEY,
        "content-type": "application/json",
        "accept": "application/json"
      },
      "body": JSON.stringify({
        name: this.state.name,
        notes: this.state.notes
      })
    })
    .then(response => response.json())
    .then(response => {
      console.log(response)
    })
    .catch(err => {
      console.log(err);
    });
  }

  update(e) {
    // update entity - PUT
    e.preventDefault();

    // this will update entries with PUT
    fetch("https://fairestdb.p.rapidapi.com/friend/friendModel", {
        "method": "PUT",
        "headers": {
            "x-rapidapi-host": "fairestdb.p.rapidapi.com",
            "x-rapidapi-key": API_KEY,
            "content-type": "application/json",
            "accept": "application/json"
        },
        "body": JSON.stringify({
            _id: this.state.id,
            name: this.state.name,
            notes: this.state.notes
        })
        })
        .then(response => response.json())
        .then(response => { console.log(response);
        })
        .catch(err => { console.log(err); });
  }

  delete(e) {
    // delete entity - DELETE
    e.preventDefault();
    // deletes entities
    fetch(`https://fairestdb.p.rapidapi.com/friend/friendModel/_id/${this.state.id}`, {
      "method": "DELETE",
      "headers": {
        "x-rapidapi-host": "fairestdb.p.rapidapi.com",
        "x-rapidapi-key": API_KEY
      }
    })
    .then(response => response.json())
    .then(response => {
      console.log(response);
    })
    .catch(err => {
      console.log(err);
    });
  }

  handleChange(changeObject) {
    this.setState(changeObject)
  }

  render() {
    return (
        <div className="container">
          <div className="row justify-content-center">
            <div className="col-md-8">
              <h2 className="display-4 text-center">Make An API Call in React</h2>
              <form className="d-flex flex-column">
                <legend className="text-center">Add-Update-Delete Friend</legend>
                <label htmlFor="name">
                  Friend Name:
                  <input
                    name="name"
                    id="name"
                    type="text"
                    className="form-control"
                    value={this.state.name}
                    onChange={(e) => this.handleChange({ name: e.target.value })}
                    required
                    />
                </label>
                <label htmlFor="notes">
                  Friend notes:
                  <input
                    name="notes"
                    id="notes"
                    type="test"
                    className="form-control"
                    value={this.state.notes}
                    onChange={(e) => this.handleChange({ notes: e.target.value })}
                    required
                    />
                </label>
                <label htmlFor="id">
                  Friend ID:
                  <input
                    name="id"
                    id="id"
                    type="text"
                    className="form-control"
                    value={this.state.id}
                    onChange={(e) => this.handleChange({ id: e.target.value })}
                    />
                </label>
                <button className="btn btn-primary" type='button' onClick={(e) => this.create(e)}>
                  Add
                </button>
                <button className="btn btn-info" type='button' onClick={(e) => this.update(e)}>
                    Update
                </button>
                <button className="btn btn-danger" type='button' onClick={(e) => this.delete(e)}>
                    Delete
                </button>
              </form>
            </div>
          </div>
        </div>
    );
  }
}

let domContainer = document.querySelector('#App');
ReactDOM.render(<App />, domContainer);

 

A few things to note:

  • all the calls are from the same form, which can cause user experience issues, but for this example, it can work
  • componentDidMount is commented out

Now, we can add, update, and delete friends from our application. Also, we can view the records that we are making using the RapidAPI dashboard to send requests and inspect the response.

How do we know that is work?

HTTP Status Codes

HTTP status codes provide information about a particular request. For example;

  • 200 – the request has succeeded
  • 201 – request successfully created something
  • 400 – bad request (syntax, parameters)
  • 401 – unauthorized
  • 404 – page not found
  • 500 – server error

Those are some of the most common. In our app, when we add check the status of requests in the developer tools.

In the Network tab, you can find the request that was just sent from the browser. Let’s try it out.

In the app add a friend to the database.

Open up the developer tools (I am using Google Chrome) and go to the Network tab.

friendModel - 200

Notice the request’s name was ‘friendModel’ and the status was 200! If a request fails, the browser may highlight the request red so it is easier to find.

We are golden in terms of sending HTTP requests with React. However, what if we want to view this data in our application? It would be much easier to make edits and see all of our friends!

How to Display API data in React

componentDidMount

Previously, we added code to componentDidMount that retrieves the records in our database. However, we did not have a way to display that data on the page, so we commented it out.

Let’s create a new component that receives the response data as a prop, and displays that data when the page loads.

Above the App component in app.js add the component:

'use strict'
class Friends extends React.Component {
    render() {
        return (
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Since</th>
                    </tr>
                </thead>
                <tbody>
                    {this.props.friends && this.props.friends.map(friend => {
                        return <tr>
                            <td>{friend._id}</td>
                            <td>{friend.name}</td>
                            <td>{friend.since}</td>
                        </tr>
                    })}
                </tbody>
            </table>
        );
    }
}
// App component

 

 

The above component is similar to App, however, it waits for this.props.friends to be defined before rendering the table rows. This is necessary because the parent component, App, needs to fetch the data. Therefore, the data will not be available when the component first mounts.

Next, add this component as a child of App and pass the property friends with the value this.state.friends.

Inside the JSX code of the App component, and underneath the closing </form> tag, add the following line.

<Friends friends={this.state.friends} />

Next, uncomment the componentDidMount function.

Finally, the friends that we have in the database will appear as rows in the table when the page loads!

friend form with list of three friends in database

This will make it easier to add, remove, and edit our friend list.

Further Considerations

User Experience

There are many ways that the form could be improved, for example, it could:

  • display success and error messages
  • clear the input after submitting
  • only allow the user to submit fields that are used by the specific API call

However, this is one of the most basic ways to make a React component and I chose this method so we could focus on the important details of building components and making API calls. Not only that, I wanted you to understand React at a basic level before using an advanced project builder.

That being said, for a small project this could be fixed up to look—and behavior—nicer with little effort.

Security

Despite instructing you to put your API-key in the front-end code for this example that is a bad idea, because it can be found if someone was looking for it. Therefore, whether you build a React app this way, or whether you use Create-React-App, if the React code is in the front-end it should not have an API-key.

This might leave you wondering, so what do I do? One example is to use a framework like Next.js that uses server-side rendering or a static site render like GatsbyJS. Unfortunately, even those solutions do not cover all scenarios so make sure you read up on what you are trying to do before you put your API key in a compromising position.

In the next section, I cover two examples of solutions for securing your app for API calls.

React API Call Examples

 

The above tutorial doesn’t use React but utilizes Netlify to make secure API requests without having to set up a backend server. Netlify offers serverless function capabilities that are not shipped with the frontend code, so API secrets can be added as environment variables later.

Reviewing the above tutorial would introduce you to an easy solution to securing third-party API requests.

 

If you are looking for more of a challenge the tutorial above is the answer. The frontend of the app is built with Create-React-App (CRA) which has been a popular choice for many when building larger React applications.

In addition to CRA, the example application sets up a backend NodeJS server that makes secure HTTP requests to a third-party API. This is another very common pattern in creating React applications and is why stacks like the M.E.R.N become popular (MongoDB, Express, React, Node).

Here’s another example using OpenWeatherMap:

 

And with Google Maps:

 

Conclusion

It’s difficult to build a React application without adding features that involve sending HTTP requests. There are many APIs that make our lives easier and it would be foolish not to utilize them! This introduction to React and API calls was brief so I hope you can sharper your skills with one of the tutorials I suggested above.

If you have any questions please leave a comment!

FAQ

How to display API data using Axios with React?

Set-up the app, add Axios API call with API Key, and transform Axios Response data. Read more here: https://rapidapi.com/blog/axios-react-api-tutorial/

What is right way to do API call in React JS?

As best place and practice for external API calls is React Lifecycle method componentDidMount(), where after the execution of the API call you should update the local state to be triggered new render() method call, then the changes in the updated local state will be applied on the component view.

How to fetch data from a GraphQL API in React?

Set up the application, fetch GraphQL data and display the response data. See more here: https://rapidapi.com/blog/graphql-react-fetch-data/

Browse the Best Free APIs List

3.5/5 – (6 votes)

API vs Microservices What’s the Difference?]

Build an IP Scanner Tool in Python with geoPlugin IP Geolocation API »

How to Use the Telize API with Python, PHP, Ruby & Javascript Examples How to Use the Telize API with Python, PHP, Ruby & Javascript Examples

How to Use the Currency Exchange API with PHP, Python, Ruby & JavaScript Examples How to Use the Currency Exchange API with PHP, Python, Ruby & JavaScript Examples

How to Use the Love Calculator API with Python, PHP, Ruby & JavaScript Examples How to Use the Love Calculator API with Python, PHP, Ruby & JavaScript Examples

Monolithic vs Microservices Comparison: Which is the Best Architecture? Monolithic vs Microservices Comparison: Which is the Best Architecture?

Flutter vs. React Native: Which Do Developers' Use More Flutter vs. React Native: Which Do Developers’ Use More

How to build a REST API with Node.js – Part 1 How to build a REST API with Node.js – Part 1

 

Filed Under: JavaScript API Tutorials, React API Tutorials, REST API Tutorials**Tagged With: how to, how to use an api, javascript, react, react.js, reactjs**

img

Jarrett Retz

Jarrett is a Web and Automation Application Developer based in Spokane, WA. He is well versed in NodeJS, React, Django, Python, MongoDB, third-party APIs (i.e Sendgrid, Stripe), PostgreSQL, HTML5, CSS3, and cloud-computing resources.

Learn more about Jarrett on his website.

Build anything with APIs, faster.

Discover, evaluate, and integrate with any API. RapidAPI is the world’s largest API Hub with over 4 Million developers and 35,000 APIs.

Browse APIs »

APIs mentioned in this article

Connect to the FaiRESTdb API

Connect to the FaiRESTdb API

https://www.digitalocean.com/community/tutorials/how-to-call-web-apis-with-the-useeffect-hook-in-react

 

https://www.digitalocean.com/community/tutorials/how-to-manage-state-on-react-class-components#step-1-%E2%80%94-creating-an-empty-project

 

https://www.digitalocean.com/community/tutorial_series/how-to-code-in-javascript

 

https://www.digitalocean.com/community/tutorials/how-to-manage-state-with-hooks-on-react-components

 

https://www.digitalocean.com/community/tutorials/how-to-handle-async-data-loading-lazy-loading-and-code-splitting-with-react

 

 

 

 

The author selected Creative Commons to receive a donation as part of the Write for DOnations program.

Introduction

In React development, web application programming interfaces (APIs) are an integral part of single-page application (SPA) designs. APIs are the primary way for applications to programmatically communicate with servers to provide users with real-time data and to save user changes. In React applications, you will use APIs to load user preferences, display user information, fetch configuration or security information, and save application state changes.

In this tutorial, you’ll use the useEffect and useState Hooks to fetch and display information in a sample application, using JSON server as a local API for testing purposes. You’ll load information when a component first mounts and save customer inputs with an API. You’ll also refresh data when a user makes a change and learn how to ignore API requests when a component unmounts. By the end of this tutorial, you’ll be able to connect your React applications to a variety of APIs and you’ll be able to send and receive real-time data.

Prerequisites

Step 1 — Creating a Project and a Local API

In this step, you’ll create a local REST API using JSON server, which you will use as a test data source. Later, you’ll build an application to display a grocery list and to add items to the list. JSON server will be your local API and will give you a live URL to make GET and POST requests. With a local API, you have the opportunity to prototype and test components while you or another team develops live APIs.

By the end of this step, you’ll be able to create local mock APIs that you can connect to with your React applications.

On many agile teams, front-end and API teams work on a problem in parallel. In order to develop a front-end application while a remote API is still in development, you can create a local version that you can use while waiting for a complete remote API.

There are many ways to make a mock local API. You can create a simple server using Node or another language, but the quickest way is to use the JSON server Node package. This project creates a local REST API from a JSON file.

To begin, install json-server:

more-
Scroll to Top