Itโ€™s a good practice to create a specific file that handles API calls. This can help keep your codebase clean and makes it easier to manage all API-related operations in one place. Create a file named api.js in your src directory:

// src/api.js

import axios from 'axios';

const API_BASE_URL = 'https://api.yourdomain.com';

const instance = axios.create({
  baseURL: API_BASE_URL,
  timeout: 1000,
});

// You can add common headers or auth tokens here
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

export const fetchData = async () => {
  try {
    const response = await instance.get('/endpoint');
    return response.data;
  } catch (error) {
    console.error('Error fetching data: ', error);
    // Handle errors here or throw them to be handled where the function is called
    throw error;
  }
};

Making an API Call from a React Component

Now you can use the fetchData function from the api.js in any React component. Hereโ€™s an example:

// src/App.js

import React, { useEffect, useState } from 'react';
import { fetchData } from './api';

function App() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetchData()
      .then(data => {
        setData(data);
        setLoading(false);
      })
      .catch(err => {
        setError(err);
        setLoading(false);
      });
  }, []);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error loading data!</p>;

  return (
    <div>
      <h1>Data Loaded</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}

export default App;

Handling Errors

As shown in the component above, error handling is crucial when making API calls. You can handle errors within the API call function, or directly within the component, depending on how you prefer to manage error states in your application.

Answer from Viram Choksi on Stack Overflow
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ react-axios-react
How To Use Axios with React | DigitalOcean
September 25, 2025 - Learn how to use Axios with React for GET, POST, and DELETE requests. Configure interceptors, hooks, and error handling.
Discussions

React.js API calls using Axios - javascript
I am trying to create a login form in react.js. I have an API where there is only username and password. Now I don't know how to call an Api in React.js. I have watched tutorials but I didn't get i... More on stackoverflow.com
๐ŸŒ stackoverflow.com
reactjs - How do I use the get request of axios by sending a query from the user and getting the values from the database for that particular query? - Stack Overflow
I am using axios to get the data from the database using the given API. Instead of using the query variable, if I use the actual name, then it works. When I use the query variable, I think it passes an empty string when the page loads because of which I get 400 error code in the console. More on stackoverflow.com
๐ŸŒ stackoverflow.com
axios get request in reactJS - Stack Overflow
I am new to the react and I am learning how to HTTP get request using axios. I am referring to a youtube video: https://www.youtube.com/watch?v=NEYrSUM4Umw and following along, but I got an error. More on stackoverflow.com
๐ŸŒ stackoverflow.com
April 6, 2020
How to make an axios get request on button click event in React?
I'm quite new to using hooks in ... the get request on the 'handleClick' prop. ... Create a function inside your app function like function update() { axios(...)... } and use useEffect(update, []); instead. Now just call update() again at any point. ... import axios from "axios"; import React, { useState, ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ how-to-use-axios-with-react
How To Use Axios With React: The Definitive Guide (2021)
July 13, 2021 - This is very similar to the .get() method, but the new resource you want to create is provided as the second argument after the API endpoint. To update a given resource, make a PUT request. In this case, you'll update the first post. To do so, you'll once again create a button. But this time, the button will call a function to update a post: import axios from "axios"; import React from "react"; const baseURL = "https://jsonplaceholder.typicode.com/posts"; export default function App() { const [post, setPost] = React.useState(null); React.useEffect(() => { axios.get(`${baseURL}/1`).then((response) => { setPost(response.data); }); }, []); function updatePost() { axios .put(`${baseURL}/1`, { title: "Hello World!", body: "This is an updated post."
๐ŸŒ
Medium
medium.com โ€บ @shriharim006 โ€บ how-to-use-axios-in-react-1429f3217dba
How to use Axios in React
July 10, 2023 - We are also using the useEffect hook to make the GET request when the component mounts. The empty array [] passed as the second argument to useEffect ensures that the effect only runs once, when the component mounts. Thatโ€™s it! You now know how to use Axios in a React application.
Top answer
1 of 3
4

Itโ€™s a good practice to create a specific file that handles API calls. This can help keep your codebase clean and makes it easier to manage all API-related operations in one place. Create a file named api.js in your src directory:

// src/api.js

import axios from 'axios';

const API_BASE_URL = 'https://api.yourdomain.com';

const instance = axios.create({
  baseURL: API_BASE_URL,
  timeout: 1000,
});

// You can add common headers or auth tokens here
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

export const fetchData = async () => {
  try {
    const response = await instance.get('/endpoint');
    return response.data;
  } catch (error) {
    console.error('Error fetching data: ', error);
    // Handle errors here or throw them to be handled where the function is called
    throw error;
  }
};

Making an API Call from a React Component

Now you can use the fetchData function from the api.js in any React component. Hereโ€™s an example:

// src/App.js

import React, { useEffect, useState } from 'react';
import { fetchData } from './api';

function App() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetchData()
      .then(data => {
        setData(data);
        setLoading(false);
      })
      .catch(err => {
        setError(err);
        setLoading(false);
      });
  }, []);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error loading data!</p>;

  return (
    <div>
      <h1>Data Loaded</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}

export default App;

Handling Errors

As shown in the component above, error handling is crucial when making API calls. You can handle errors within the API call function, or directly within the component, depending on how you prefer to manage error states in your application.

2 of 3
1

Assuming that you have basic knowledge of React and how the states work.

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

const Page = () => {
  const [name, setName] = useState('');
  const [password, setPassword] = useState('');


  const handleSubmit = async (event) => {
    event.preventDefault();

    try {
      const response = await axios.post('/api', {
        name,
        password,
      });
      console.log('Login successful:', response.data);
    } catch (error) {
      console.error('Login error:', error);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label htmlFor="name">Name:</label>
        <input
          type="text"
          id="name"
          value={name}
          onChange={(event) => setName(event.target.value)}
        />
      </div>
      <div>
        <label htmlFor="password">Password:</label>
        <input
          type="password"
          id="password"
          value={password}
          onChange={(event) => setPassword(event.target.value)}
        />
      </div>
      <button type="submit" onClick = {handleSubmit}>Login</button>
    </form>
  );
};

export default Page;

This is the basic API call using Axios by taking the user input and sending it as payload.

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ axios-in-react-a-guide-for-beginners
Axios in React: A Guide for Beginners - GeeksforGeeks
Supports making GET, POST, PUT, DELETE, and other HTTP requests. Before you install Axios your React project app should be ready to install this library.
Published ย  March 21, 2025
๐ŸŒ
Codedamn
codedamn.com โ€บ news โ€บ react js
Using Axios with React to make GET, POST, and DELETE API Requests
June 4, 2023 - In this example, we've created a fetchData function that uses Axios to make a GET request to the JSONPlaceholder API. The fetched data is then stored in the data state variable, which is initially set to an empty array.
Find elsewhere
๐ŸŒ
Geekster
geekster.in โ€บ home โ€บ axios in react
https://www.geekster.in/articles/axios-in-react/
June 19, 2024 - useEffect Hook: Use the useEffect hook to perform side effects in your functional component. Here, Axios GET request is made inside useEffect with an empty dependency array ([]) to ensure it runs once when the component mounts.
๐ŸŒ
GitHub
github.com โ€บ axios โ€บ axios
GitHub - axios/axios: Promise based HTTP client for the browser and node.js ยท GitHub
1 week ago - Newer Axios separates these concerns: to allow the // XSRF header to be sent for cross-origin requests you should set both // `withCredentials: true` and `withXSRFToken: true`. // // Example: // axios.get('/user', { withCredentials: true, withXSRFToken: true }); // `onUploadProgress` allows handling of progress events for uploads // browser & node.js onUploadProgress: function ({loaded, total, progress, bytes, estimated, rate, upload = true}) { // Do whatever you want with the Axios progress event }, // `onDownloadProgress` allows handling of progress events for downloads // browser & node.js
Starred by 109K users
Forked by 11.6K users
Languages ย  JavaScript 86.5% | TypeScript 11.6% | HTML 1.9%
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 71506569 โ€บ how-do-i-use-the-get-request-of-axios-by-sending-a-query-from-the-user-and-getti
reactjs - How do I use the get request of axios by sending a query from the user and getting the values from the database for that particular query? - Stack Overflow
function AdminMemberSearchFirstName({ name }) { const [data, setData] = useState([]); const [query, setQ] = useState(""); function queryGiven(query) { setQ(query); } async function getFilteredData() { axios.get(`admin/member/firstname/${query}`).then((response) => { console.log(response.data); setData(data); }); } useEffect(() => { getFilteredData(name); }, []); return ( <div> <FirstNameForm queryGiven={queryGiven} /> <h1>{query}</h1> </div> ); }
๐ŸŒ
Axios
axios-http.com โ€บ docs โ€บ intro
Getting Started | Axios Docs
Promise based HTTP client for the browser and node.js ยท Axios is a promise-based HTTP Client for node.js and the browser. It is isomorphic (= it can run in the browser and node.js with the same codebase). On the server-side it uses the native node.js http module, while on the client (browser) ...
๐ŸŒ
Upgrad
upgrad.com โ€บ home โ€บ blog โ€บ software development โ€บ 2025 guide to axios in react: build better web apps!
Axios in React: Key Techniques Every Beginner Must Know!
June 27, 2025 - Once the request is made, letโ€™s look at how to handle the responses effectively with Axios in React. After making an API request, you can use the .then() method to handle successful responses and access the returned data.
๐ŸŒ
DEV Community
dev.to โ€บ femi_akinyemi โ€บ how-to-use-axios-with-react-5fom
How to use Axios with React - DEV Community
September 14, 2022 - This tutorial demonstrated how Axios could be used inside a React application to create HTTP requests and handle responses.
๐ŸŒ
OpenReplay
blog.openreplay.com โ€บ axios-react-get-post
Using Axios in React: Examples for GET and POST Requests
Axios simplifies HTTP requests in React with a clean API. It supports promises, enabling efficient asynchronous operations. GET requests retrieve data; POST requests send data to servers.
๐ŸŒ
npm
npmjs.com โ€บ package โ€บ axios
axios - npm
5 days ago - // Send a GET request (default method) axios("/user/12345");
      ยป npm install axios
    
Published ย  Apr 08, 2026
Version ย  1.15.0
๐ŸŒ
LinkedIn
linkedin.com โ€บ pulse โ€บ fetching-data-axios-react-explained-khaled-bellal-
Fetching Data with Axios in React
May 8, 2023 - By using the `axios.get()` method ... in our React components. In conclusion, using Axios with React is a powerful combination for making HTTP requests and fetching data from APIs....