Easy steps to get data from API in React

Table of contents

a computer screen with a logo on it

I remembered working on a project last year that dealt with fetching my GitHub repository using the API. I started just a few days before the deadline, and I needed to pull off a miracle.

Before that, I had no prior knowledge of how to fetch data from the API, so I went on the internet and searched for beginner videos and articles on what to do. If this is you, then you are reading the right article, because it will be as simple as possible for you to understand.

You would be using a simple approach that requires no installation. Follow the step-by-step beginner's guide to successfully get your data.

API data fetch

Step 1: create react app using your terminal or gitbash

npx create-react-app [name-of-your-project]

npx create-react-app data-fetching

Step 2: Navigate to the App.js file

Edit App.js to remove unnecessary content. Or you might create another component for this project (don't forget to add the extension ".js" or ".jsx").


import './App.css';

function App() {
  return (
    <div className="App">

    </div>
  );
}

export default App;

Step 3: Import useState and useEffect from react

useState is used for state management, and useEffect is used for data fetching when the component mounts.

import { useState, useEffect } from 'react';

Step 4: Fetch the data

import { useState, useEffect } from "react";
import "./App.css";

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

  const fetchPosts = () => {
    fetch("https://dummyjson.com/posts")
      .then((response) => {
        return response.json();
      })
      .then((data) => {
       setPosts(data.posts);
      });
  };

  useEffect(() => {
    fetchPosts();
  }, []);

  return <div className="App"></div>;
};

export default App;

To test if this is working, type console.log the data and inspect it in the web browser. You should have the image below on your console.

return (
    <div className="App">
     {console.log(posts)}
    </div>
  );

Why is the code below not written instead of the one above? Focus on the setPosts .

It's because you can only map an array. Writing the code below will display an object, and trying to map it will display an error.

const fetchPosts = () => {
    fetch(" https://dummyjson.com/posts")
      .then((response) => {
        return response.json();
      })
      .then((data) => {
       setPosts(data);
      });
  };

The array of this API is found in the .posts (check the image above). That is why data.posts is appended to setPosts to display the array.

Step 5: Create a new component and loop through the data to it.

 return (
    <div className="App">
     {posts.map((post) => (<EachCart key={post.id} post={post}/>))}
    </div>
  );
import React from 'react'

function EachCart(posts) {
  return (
    <div>
        <h2>{posts.post.title}</h2>
        <p>{posts.post.body}</p>
    </div>
  )
}

export default EachCart

You can do all these in the app.js file, but breaking down your codes into smaller components makes it easier to go through and prevents cumbersome codes all in one component.

Then apply your styling.


Viola!!! Congratulations on successfully fetching your data.

I hope these steps were easy enough for you to comprehend.

Feel free to reach out if you have questions, and watch this space for more articles.