DEV Community

Apollo Fredrick
Apollo Fredrick

Posted on

React API calls made simple with Axios

React is a JavaScript library for building user interfaces. Often you will want to fetch data from an API and display it in your React application.
Axios is a promise-based HTTP client that makes it easy to fetch data from APIs.
In this tutorial I will show you the simplest way to fetch API data and display it in your website.

Prerequisites

You should have a basic knowledge of React

Install Axios

Install Axios in your project folder using the following command:

npm install axios
Enter fullscreen mode Exit fullscreen mode

Import Axios

Import Axios in the component which you want to make API calls in as shown below:

import React, { useEffect, useState } from 'react';
import axios from 'axios';
Enter fullscreen mode Exit fullscreen mode

Making a GET Request

To make a GET request, use the following code:

axios.get(url)
  .then(response => {
    // Handle the successful response here
    console.log(response.data);
  })
  .catch(error => {
    // Handle errors here
    console.error('Error fetching data:', error);
  });
Enter fullscreen mode Exit fullscreen mode

Handling Asynchronous Operations

To handle asynchronous functions we use 'async/await' since API calls are asynchronous operations and React ensures that the UI remains responsive during these calls:

const fetchData = async() =>{
      try {
        const response = await axios.get(url)
        setData([response.data])
      } catch (error) {
        console.log(error)
      }
    }
    fetchData()
Enter fullscreen mode Exit fullscreen mode

Integrate with React Components

Integrate your knowledge of data fetching in your React components as shown below:

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

const App = () => {
  const [data, setData] = useState([])
  const url = "https://api.chucknorris.io/jokes/random"

  useEffect(() => {
    const fetchData = async() =>{
      try {
        const response = await axios.get(url)
        setData([response.data.value])
      } catch (error) {
        console.log(error)
      }
    }
    fetchData()
  }, [])
  return (
    <ul>
      {data.map((item, index) => (
        <li key={index}>{item}</li>
      ))}
  </ul>
  )
}

export default App

Enter fullscreen mode Exit fullscreen mode

We use the useEffect hook to call the API when the component mounts.
Axios makes the Get request and returns a promise. When the promise resolves, we set the state using setData.
We finally use the map function to loop the data and display it on the page.
Remove React.StrictMode in your index.js file(If you are using Create-React-App) or main.js file(If you are using Vite) to prevent the useEfect hook from running twice.
Refresh the page to get more Chuck Norris jokes.

Top comments (1)

Collapse
 
marlo-bb profile image
ِMarlo Ber

**_import React, { useState, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';

function Nav() {
const [isMenuOpen, setIsMenuOpen] = useState(false);
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [userName, setUserName] = useState('');
const [userId, setUserId] = useState(null);
const navigate = useNavigate();

useEffect(() => {
const user = JSON.parse(localStorage.getItem('user'));
if (user) {
setIsLoggedIn(true);
setUserName(user.fullName || 'user*``*');
setUserId(user.id);
}

const handleStorageChange = () => {
  const currentUser = JSON.parse(localStorage.getItem('user'));
  if (currentUser) {
    setIsLoggedIn(true);
    setUserName(currentUser.fullName || 'user');
    setUserId(currentUser.id);
  } else {
    setIsLoggedIn(false);
    setUserName('');
    setUserId(null);
  }
};

window.addEventListener('storage', handleStorageChange);
return () => {
  window.removeEventListener('storage', handleStorageChange);
};
Enter fullscreen mode Exit fullscreen mode

}, []);

const handleLogout = () => {
localStorage.removeItem('user');
setIsLoggedIn(false);
setUserName('');
setUserId(null);
window.dispatchEvent(new Event('storage'));
navigate('/login');
};

return (


      <div className="text-xl font-bold text-gray-800 flex  items-center gap-2">
        <img src="https://www.shutterstock.com/image-illustration/rick-morty-get-schwifty-260nw-1736329532.jpg" alt="Logo" className="w-15 h-15 rounded-full" />

      </div>


      <div className="hidden md:flex space-x-6">
        <Link to="/home" className="text-cyan-700 font-bold hover:text-cyan-700 transition">Home</Link>
        <Link to="/welcome" className="text-cyan-700  font-bold hover:text-cyan-700 transition">Characters</Link>

        {isLoggedIn && (
          <Link
            to={`/profile/${userId}`}
            className="text-cyan-700  font-bold hover:text-cyan-700 transition"
          >
            Profile
          </Link>
        )}
      </div>


      <div className="hidden md:flex space-x-2 items-center">
        {isLoggedIn ? (
          <>
            <span className="text-black font-medium">hi، {userName}</span>
            <button
              onClick={handleLogout}
              className="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600 transition"
            >
              Logout
            </button>
          </>
        ) : (
          <>
            <Link
              to="/login"
              className="px-4 py-2 bg-cyan-900 text-white rounded hover:bg-cyan-600 transition"
            >
              Login
            </Link>
            <Link
              to="/"
              className="px-4 py-2 bg-black text-white rounded hover:bg-gray-600 transition"
            >
              Register
            </Link>
          </>
        )}
      </div>

      {/* Mobile Menu Button */}
      <div className="md:hidden flex items-center">
        <button
          onClick={() => setIsMenuOpen(!isMenuOpen)}
          className="text-black focus:outline-none"
        >
          <svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
          </svg>
        </button>
      </div>
    </div>

    {/* Mobile Menu */}
    {isMenuOpen && (
      <div className="md:hidden mt-4 pb-3 border-t border-gray-200">
        <div className="flex flex-col space-y-3">
          <Link to="/home" className="text-cyan-700  font-bold hover:text-cyan-700">Home</Link>
          <Link to="/welcome" className="text-cyan-700  font-bold hover:text-cyan-700">Characters</Link>

          {isLoggedIn && (
            <Link
              to={`/profile/${userId}`}
              className="text-cyan-700  font-bold hover:text-cyan-700"
            >
              Profile
            </Link>
          )}

          <div className="flex flex-col space-y-2 pt-2">
            {isLoggedIn ? (
              <>
                <p className="px-4 py-2 text-black">hi، {userName}</p>
                <button
                  onClick={handleLogout}
                  className="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600 text-center"
                >
                  Logout
                </button>
              </>
            ) : (
              <>
                <Link
                  to="/login"
                  className="px-4 py-2 bg-cyan-900 text-white rounded text-center hover:bg-cyan-600"
                >
                  Login
                </Link>
                <Link
                  to="/"
                  className="px-4 py-2 bg-black text-white rounded text-center hover:bg-gray-800"
                >
                  Register
                </Link>
              </>
            )}
          </div>
        </div>
      </div>
    )}
  </div>
</nav>

);
}

export default Nav;_**