DEV Community

Cover image for React Data Fetching: Axios
Abayomi Ogunnusi
Abayomi Ogunnusi

Posted on

React Data Fetching: Axios

Hello there, today we'll go over how to get data in React in the simplest way possible utilizing React Hooks (useState and useEffect), the axios library, and a mock API (JSON Placeholder

Let's fetch some data, shall we?
fetch

Make a directory and create a react app with this command
npx create-react-app .

Install the axios package: npm install axios


Create a new component and call it whatever you like. I'll call it 'Fetching' for the purposes of this lesson.
Image description

import React from "react";

const Fetching = () => {
  return (
    <div>
      <h1>Fetching my Data</h1>
    </div>
  );
};

export default Fetching;
Enter fullscreen mode Exit fullscreen mode

Now we need to construct the method that will retrieve our data from the API.

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

function Fetching() {
  const [posts, setPosts] = useState([]);
  useEffect(() => {
    axios
      .get(`https://jsonplaceholder.typicode.com/posts`)
      .then((res) => {
        console.log(res);
        setPosts(res.data);
      })
      .catch((err) => {
        console.log(err);
      });
  }, []);
  return (
    <div className="output">
      <h1>Data Fetching </h1>
      <ul>
        {posts.map((post) => (
          <li key={post.id}>
            <p>Post id: {post.id}</p>
            {post.title}
          </li>
        ))}
      </ul>
    </div>
  );
}

export default Fetching;

Enter fullscreen mode Exit fullscreen mode

Import Fetching into your app

import "./App.css";
import Fetching from "./Fetching";

function App() {
  return (
    <div className="App">
      <Fetching />
    </div>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

Source Code link: Click

Conclusion

I hope you found this article useful. Read more about React Js here:

Discussion (9)

Collapse
lukeshiru profile image
Luke Shiru • Edited on

You can just use fetch which is compatible with every supported browser out there (if it doesn't work for a user, that means they are using an unsupported browser, which isn't your problem because supporting that would be like supporting Windows 3.1). And in the node side, you can just use node-fetch. Your code would look like this instead:

import { useEffect, useState } from "react";

export const Fetching = () => {
    const [posts, setPosts] = useState([]);

    useEffect(
        () =>
            void fetch(`https://jsonplaceholder.typicode.com/posts`)
                .then(response => response.json())
                .then(({ data }) => setPosts(data))
                .catch(console.error),
        [],
    );

    return (
        <div className="output">
            <h1>Data Fetching </h1>
            <ul>
                {posts.map(post => (
                    <li key={post.id}>
                        <p>Post id: {post.id}</p>
                        {post.title}
                    </li>
                ))}
            </ul>
        </div>
    );
};
Enter fullscreen mode Exit fullscreen mode

If you're using axios just because you like their "API", then there are great alternatives out there such as redaxios by developit (the creator of preact), and if you're working with react, you could just use great libraries such as react-query.

Cheers!

Collapse
jamesthomson profile image
James Thomson

Honest question, what's so wrong with using Axios that you'd opt to use Redaxios - a lib that hasn't had any releases for a year? To me that's a red flag.

Also, React-Query is amazing, but doesn't have anything built in for handling XHR so you'd still need Fetch or something like Axios.

Collapse
lukeshiru profile image
Luke Shiru • Edited on

TBH I don't use either axios or redaxios, I just recommend redaxios because is way lighter and closer to just use fetch than axios. I personally just use fetch and react-query. Not to mention than with frameworks like Remix popping up, we don't even need that 😅

Collapse
felipeazucares profile image
Phil Suggars

Nice clear and concise article - great work. My only question (as others have picked up) is why you'd use Axios over the built in fetch? I've used both (not extensively) but in my limited experience there's little to chose between them. What's your thinking here?

Collapse
drsimplegraffiti profile image
Abayomi Ogunnusi Author

I just feel it is an overall preference of one over the other.... i will use any one that does the job perfectly. Thanks for your question

Collapse
jonrandy profile image
Jon Randy

Wouldn't a simpler way be to just use the built-in fetch instead of importing axios?

Collapse
neoprint3d profile image
Drew Ronsman

I was thinking the same thing but I my application I used fetch but it wouldn't work, but using axios it worked

The thing it was calling was a email verification API on heroku

Collapse
drsimplegraffiti profile image
Abayomi Ogunnusi Author

@lukeshiru thanks for your massive contribution.... All points noted

Collapse
drsimplegraffiti profile image
Abayomi Ogunnusi Author

@jonrandy you are correct. I decided on axios over fetch for backward compatibility reasons. Fetch can equally do the trick too. Thanks for your contribution