Using Fetch Api In React To Get Api Data React News App Tutorial

Posted on July 12, 2026 by Vishesh Namdev
Python C C++ Javascript React JS
Using Fetch API in React to Get API Data React News App Tutorial

Using Fetch API in React to Get Real News Data 🌐 So far in our News App, we have been showing hardcoded static articles. It's time to make it real — by fetching live data from an actual News API using the browser's built-in Fetch API inside React's componentDidMount lifecycle method.

In this tutorial, we will learn:

  • What is the Fetch API?
  • What is componentDidMount and why we use it for API calls?
  • How to fetch data from a REST API in a React Class Component
  • How to store API response in state
  • How to show a loading indicator while data is being fetched
  • Displaying real news articles in our NewsItem component
  • What is the Fetch API?

    The Fetch API is a built-in browser feature that lets you make HTTP requests to servers and get data back — without installing any extra library. It works with Promises, so we use .then() to handle the response, or we can use async/await for cleaner code.

    // Basic Fetch API example
    fetch("https://api.example.com/data")
      .then((response) => response.json())
      .then((data) => console.log(data))
      .catch((error) => console.error("Error:", error));
    ---

    Why Use componentDidMount for API Calls?

    In a React Class Component, componentDidMount runs after the component first appears on the screen. It is the perfect place to fetch data because:

  • The component is already mounted and ready to receive state updates.
  • Calling setState inside it triggers a re-render to display the fresh data.
  • It runs only once on the initial load — no unnecessary repeated calls.
  • ---

    Step 1: Get a Free API Key from NewsAPI

    We will use NewsAPI.org — a free REST API that returns real news articles.

    • Go to newsapi.org and create a free account.
    • Copy your API Key from the dashboard.
    • The free plan works on localhost — perfect for development.

    The API URL we will use looks like this:

    https://newsapi.org/v2/top-headlines?country=in&apiKey=YOUR_API_KEY
    ---

    Step 2: Update the News Component to Fetch Data

    Now let's update our News.js class component. We will:

  • Add a loading flag to state
  • Use componentDidMount to call the API
  • Store the fetched articles in state
  • import React, { Component } from "react";
    import NewsItem from "./NewsItem";
     
    export class News extends Component {
      state = {
        articles: [],
        loading: true,
      };
     
      async componentDidMount() {
        const apiKey = "YOUR_API_KEY_HERE"; // 🔑 Replace with your NewsAPI key
        const url = `https://newsapi.org/v2/top-headlines?country=in&apiKey=${apiKey}`;
     
        const response = await fetch(url);
        const data = await response.json();
     
        this.setState({
          articles: data.articles,
          loading: false,
        });
      }
     
      render() {
        return (
          <div className="container my-4">
            <h2 className="text-center mb-4">Top Headlines 📰</h2>
     
            {this.state.loading && (
              <div className="text-center my-5">
                <div className="spinner-border text-warning" role="status">
                  <span className="visually-hidden">Loading...</span>
                </div>
                <p className="mt-2">Fetching latest news...</p>
              </div>
            )}
     
            {!this.state.loading &&
              this.state.articles.map((article, index) => (
                <NewsItem
                  key={index}
                  title={article.title}
                  description={article.description}
                  imageUrl={article.urlToImage}
                  newsUrl={article.url}
                />
              ))}
          </div>
        );
      }
    }
     
    export default News;
    ---

    Step 3: Update NewsItem to Handle Missing Images

    Sometimes a news article has no image. Let's make NewsItem handle that gracefully with a placeholder image as a fallback.

    import React from "react";
     
    function NewsItem({ title, description, imageUrl, newsUrl }) {
      return (
        <div className="card my-3">
          <img
            src={
              imageUrl ||
              "https://via.placeholder.com/600x300?text=No+Image+Available"
            }
            className="card-img-top"
            alt={title || "News"}
            onError={(e) => {
              e.target.src =
                "https://via.placeholder.com/600x300?text=No+Image+Available";
            }}
          />
          <div className="card-body">
            <h5 className="card-title">{title || "No title available"}</h5>
            <p className="card-text">
              {description || "No description available for this article."}
            </p>
            <a
              href={newsUrl}
              target="_blank"
              rel="noreferrer"
              className="btn btn-sm btn-warning"
            >
              Read More
            </a>
          </div>
        </div>
      );
    }
     
    export default NewsItem;
    ---

    Step 4: App.js Stays the Same ✅

    No changes needed in App.js — it already imports and renders both Navbar and News correctly from our previous tutorial.

    import React from "react";
    import Navbar from "./components/Navbar";
    import News from "./components/News";
     
    function App() {
      return (
        <div>
          <Navbar />
          <News />
        </div>
      );
    }
     
    export default App;
    ---

    Step 5: Run Your App and See Real News!

    npm start

    Open http://localhost:3000 in your browser. You will see a loading spinner for a moment, and then real live news articles from India will appear — fetched directly from the NewsAPI! 🎉

    ---

    ⚠️ Important Note:
    Never expose your API key directly in your frontend code in production. Anyone can view it in the browser. For production apps, always call the API from a backend server and keep your key in an environment variable (.env file). For this beginner tutorial and local development, using it directly is perfectly fine.

    ---

    Features and Learnings:-

  • Learned what the Fetch API is and how it works with Promises.
  • Understood why componentDidMount is the right place for API calls in Class Components.
  • Used async/await inside componentDidMount to fetch real news data.
  • Stored the API response inside React state using setState.
  • Added a loading spinner that shows while the data is being fetched.
  • Updated NewsItem to handle missing images and descriptions gracefully.
  • Displayed real live news articles in our News App from NewsAPI.org.
  • 📢 Important Note 📢

    How did you feel about this post?

    😍 🙂 😐 😕 😡

    Was this helpful?

    👍 👎