React: How to Make API Calls Using the useEffect Hook
Dennis Maina
Dennis Maina

Published on 11th October, 2022 (1 year ago) ● Updated on 11th October, 2022

React: How to Make API Calls Using the useEffect Hook

(2 minutes read)

React Hooks are functions that let you “hook into” React state and lifecycle features from function components. Hooks don't work inside classes — they let you use React without classes.

Examples of hooks include useStateuseEffect, and useRef.

This post will show you how to make API calls using the useEffect hook. The useEffect hook does for React functional component (s) what componentDidMount() does for react class component (s).

Inside your functional component, import useEffect and useState by adjusting your react import line with the following:

import React, { useEffect, useState,  } from "react";

Import axios:

import axios from "axios";

Set an initial state for data:

const [backendData, setBackendData] = useState("");

Just above the return statement, declare the useEffect function:

  useEffect(() => {

  }, [])

The empty array (that is, []) is important to avoid continuous execution after an API call has been completed.

In the function, set the following configurations:

  useEffect(() => {
    // set configurations for the API call here
    const configuration = {
      method: "get",
      url: "http://localhost/PORT/YOUR_ENPOINT",
    };
  }, [])

Next, make the API call using axios:

  // useEffect automatically executes once the page is fully loaded
  useEffect(() => {
    // set configurations for the API call here
    const configuration = {
      method: "get",
      url: "http://localhost/PORT/YOUR_ENPOINT",
    };

    // make the API call
    axios(configuration)
      .then((result) => {
        // assign the data in our result to the backendData we initialized above
        setBackendData(result.data.message);
      })
      .catch((error) => {
        error = new Error();
      });
  }, [])

setBackendData(result.data.message); assigns the message in the result (that is, result.data.message) to the backendData initialized above. Now you can display the backendData in your component.

To display the backendData that you got on the component page, enter the following code below the h1 tag:

<h3 className="text-center text-danger">{backendData}</h3>

React will read the backendData as a variable because of the curly brackets. If the backendData is without the curly brackets, React reads it as a string.

This your component file at this point:

import React, { useEffect, useState } from "react";
import axios from "axios";

export default function FreeComponent() {
  // set an initial state for the backendData we will receive after the API call
  const [backendData, setBackendData] = useState("");

  // useEffect automatically executes once the page is fully loaded
  useEffect(() => {
    // set configurations for the API call here
    const configuration = {
      method: "get",
      url: "http://localhost/PORT/YOUR_ENPOINT",
    };

    // make the API call
    axios(configuration)
      .then((result) => {
        // assign the backendData in our result to the message we initialized above
        setBackendData(result.data.message);
      })
      .catch((error) => {
        error = new Error();
      });
  }, []);

    return (
    <div>
      <h1 className="text-center"> Component</h1>

      {/* displaying our message from our API call */}
      <h3 className="text-center text-danger">{backendData}</h3>
    </div>
  );
}
    

Comments (0)

Dennis Maina

Dennis Maina

https://dentricedev.com

CEO and Founder of DentriceDev Solutions.

24

Articles

July '22

Joined date

Domain Name Registration & Hosting
Domain Name Registration & Hosting

HostPinnacle Kenya is the best and cheapest web hosting company in Kenya with world-class web hosting packages and affordable web design offers. Apart from that we offer free life-time SSL certificate, affordable domain registration in Kenya and free whois privacy. We have an award-winning support team available 24/7/365 to help you with your queries.

Ready to Elevate Your Digital Presence?
Ready to Elevate Your Digital Presence?

Whether you're looking to launch a cutting-edge mobile app, revamp your website with sustainable web design, or harness the power of AI and digital marketing to outshine your competition, we're here to turn your vision into reality. At DentriceDev, we blend innovation, expertise, and passion to deliver digital solutions that drive results. Don't let your business get left behind in the digital revolution. Reach out to us today, and let's create something remarkable together. Connect with us directly at [email protected], give us a call or WhatsApp at +254 757 927190, or simply fill out our contact form to get started. Your digital future awaits, and we're excited to be part of your journey!

Do you want to write with us? Register and start blogging.

Register Login

Thank you for your support!

We deliver the best web products