Using a REST API in react

Using a REST API in react:

WHAT IS AN API

An API stands for an “Application Programming Interface”. It allows communication between softwares and provides ways of sharing data between applications. The REST API stands for “Representational State Transfer”.

REST API is a software architectural style that defines a set of constraints and allows communication with RESTful web service. The REST API uses the HTTP request method to access and use data.

API METHODS

Below are the REST API methods:

  • Get Method: As the name implies, it gets the data directly from the API.

  • Post Method: The post method is used to give back data collected from the application to the server or an API.

  • Put Method: This action is used to make changes and update a request.

  • Delete Method: This method is used to eradicate pieces of information or data that are not needed.

    For this article, we are using a free API to demonstrate how to use the API call in react.

PROJECT SETUP:

Run this code in your command prompt to create a new react app.
npx create-react-app api-usage
then cd into the app:
cd api-usage
run yarn start or npm start 
yarn start
npm start

You should see the react logo spinning in your browser

API FOR THIS PROJECT:

link to api: icanhazdadjoke.com

In this project, we are going to use Axios. Axios is used for making HTTP requests and used for fetching data from an API or a database or XMLRequests.
Run: npm i axios

Inside your App.js get rid of everything and it should look like this:

import React from 'react';
import './App.css';

function App() {

  return (
    
{/*No component yet*/}
); } export default App;

Then inside the src folder create a new component Joke.js.Since we installed Axios earlier we are going to import it into our app.

import React from 'react';
import axios from 'axios';

const Joke = () => {
return (
   

Jokes:

); } export default Joke;

From the code above:

We are creating a new Joke component and rendering an h1, then we export the Joke component by default.

Next, we import the Joke component into the App.js component so that it can be displayed in the browser.

import React from 'react';
import Joke from './Joke';
import './App.css';

function App() {

  return (
    
{/*Joke component*/}
); }

In your browser, you should see Joke: displaying on the screen:

Next, I am going to show how to use the API in our code.

import React, {useState} from 'react';
import axios from 'axios';

function Joke = () => {
     //create a state to store the jokes from the api
const [joke, setJoke]  useState([]); //make sure you to import useState from react

//store the api in a variable
    const apiLink = "https://icanhazdadjoke.com/";

//create a function to fetch the data
 const fetchData = async () => {
        const res = await axios.get(`${apiLink}`, { headers: { Accept: "application/json" } });
        console.log(res.data);
        console.log(res.data.joke)
    }

return (
   

Jokes:

); } export default Joke;

From the code above:

I created a state const [joke, setJoke] = useState([])
to store the data from the api and created a function fetchData 
to fetch data from the api that was stored in the variable 
const apiLink = "https://icanhazdadjoke.com/"; then created the response variable const res = await axios.get(${apiLink}, { headers: { Accept: "application/json" } }).
We use async and await to wait for the data any time it fetches it. We also logged the data to the browser console so we can see what we fetched from the API. If you open your browser console by pressing f12 you will see the data from the API in an object {data}.

Next we are going to be displaying the jokes inside our browser.
Let’s go 🚀🚀🚀…

//imports ....

const Joke = () => {
    const [joke, setJokes] = useState([]);


    const apiLink = "https://icanhazdadjoke.com/";

    const fetchData = async () => {
        const res = await axios.get(`${apiLink}`, { headers: { Accept: "application/json" } });
        console.log(res.data.joke);
        setJokes([res.data.joke]);
    }
    return (
        

Jokes:

{/*Fetch data from url*/} Load jokes {/*data from api goes here*/} {joke && joke.map((j, index) => (
{j}
))}
) } export default Joke;

From the code above:

In the fetchData function, we set the state to the response of every joke we get from the API setJokes([res.data.joke]);.In the return statement we passed in the fetchData function to a button, for any time we click the button it loads new jokes Load jokes.

From the code below:

We are mapping through the joke array if there is any joke, and returning the joke from the API in a div.

  {/*data from api goes here*/}
                    {joke && joke.map((j, index) => (
                         
{j}
))}

Now start your app you would see Joke: and Load jokes displaying. When you click on the Load jokes button new jokes are displayed. It should look like this:

Summary:

In this article, we have seen how to use a REST API in react. By using the GETmethod to get data from the API icanhazdadjoke.com in JSON format then incorporating that data into our application.

from Tumblr https://generouspiratequeen.tumblr.com/post/638926047071682560

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s