← Back to React Course | Chapter 10: Data Fetching & Async | Lesson 2 of 10

Using Axios in React

Axios is like a fancier version of fetch that automatically translates the response into plain data for you and gives clearer error messages when something goes wrong.

Making a GET Request with Axios

axios.get(url) sends a GET request and returns a Promise that resolves directly to the parsed response data (under response.data), skipping the extra .json() step fetch() requires. This slightly shorter, more consistent API is one of axios's main appeals.

Note: response.data holds the actual payload; response.status and response.headers are also available if needed.

Warning: Unlike fetch(), axios's Promise DOES reject automatically on HTTP error statuses (4xx/5xx) — no manual response.ok check needed, but you do need a .catch().

Example: Making a GET Request with Axios

markup
// Run in your local React project (npm install required)
import axios from 'axios';

function App() {
  const [data, setData] = React.useState(null);
  React.useEffect(() => {
    axios.get('/api/data').then(response => setData(response.data));
  }, []);
  return <p>{data ? data.message : "Loading..."}</p>;
}

⚠️ This example uses an npm package with no CDN build available here — run this in your local React project.

Handling Errors with Axios

Because axios automatically rejects on HTTP error statuses, a .catch() block (or a try/catch with async/await) reliably catches both network failures and server error responses in one place, simplifying error handling compared to fetch's manual response.ok check.

Note: error.response.status gives the HTTP status code when the server responded with an error; error.response is undefined for pure network failures.

Warning: Forgetting a .catch() (or try/catch) with axios means an unhandled promise rejection on any failed request, unlike fetch which needs an extra explicit check to even notice the failure.

Example: Handling Errors with Axios

markup
// Run in your local React project (npm install required)
import axios from 'axios';

async function loadData(setError) {
  try {
    const response = await axios.get('/api/data');
    return response.data;
  } catch (error) {
    setError(error.message);
  }
}

⚠️ This example uses an npm package with no CDN build available here — run this in your local React project.

Creating a Reusable Axios Instance

axios.create() builds a pre-configured instance with settings like a baseURL and default headers, so you don't repeat the full API URL and auth header on every single request. This instance is created once and imported wherever needed throughout the app.

Note: Set a baseURL once in the instance, then call api.get('/users') instead of api.get('https://api.example.com/users') everywhere.

Warning: Create the instance once at module scope (in its own file), not inside a component — recreating it on every render loses any benefit.

Example: Creating a Reusable Axios Instance

markup
// Run in your local React project (npm install required)
import axios from 'axios';

const api = axios.create({
  baseURL: 'https://api.example.com',
  headers: { Authorization: 'Bearer token123' },
});

// Later, anywhere in the app:
// api.get('/users').then(response => console.log(response.data));

⚠️ This example uses an npm package with no CDN build available here — run this in your local React project.

Common Mistakes
  1. Forgetting axios responses are already parsed — accessing response.data, not calling .json() like with fetch.
  2. Not catching axios errors, which (unlike fetch) DOES reject on HTTP error statuses by default.
  3. Creating a new axios instance on every render instead of configuring it once outside the component.
Chapter Summary
  • Axios is a popular third-party HTTP client, offering a friendlier API than the built-in fetch().
  • Unlike fetch, axios automatically parses JSON responses and rejects its promise on HTTP error statuses.
  • axios.get/post/put/delete map directly to the corresponding HTTP methods.
  • axios.create() lets you configure a reusable instance with a base URL and default headers.
Browser Support

Requires npm install axios — not available via CDN in this sandbox; works with any React version.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.