Practice: Basic Hooks useEffect With 3rd-party API

Understanding the Problem

We aim to create a React component that fetches data from the Fortnite API's news endpoint and displays it. This involves:

Devising a Plan

To tackle this problem, we'll follow these steps:

  1. Set up the React project environment.
  2. Create a component named ServerData.
  3. Within ServerData, initialize a state variable serverData with its setter function setServerData.
  4. Use the useEffect hook to fetch data from the Fortnite API upon component mount.
  5. Parse the fetched data to extract relevant information.
  6. Render the extracted data within the component.

Implementing the Solution

Let's delve into the implementation of the ServerData component.

1. Setting Up the React Project

Ensure you have Node.js installed. Then, set up the project:

npx create-react-app fortnite-news
cd fortnite-news
npm install

2. Creating the ServerData Component

In the src directory, create a file named ServerData.jsx with the following content:

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

const ServerData = () => {
  const [serverData, setServerData] = useState(null);

  useEffect(() => {
    const fetchFortnite = async () => {
      try {
        const response = await fetch('https://fortnite-api.com/v2/news');
        const data = await response.json();
        const newsArray = data.data.br.motds;
        setServerData(newsArray);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };
    fetchFortnite();
  }, []);

  if (!serverData) return <h1>No Data To Display</h1>;

  return (
    <div>
      {serverData.map((newsItem) => (
        <div className='serverContainer' key={newsItem.id}>
          <h1 className='title'>{newsItem.title}</h1>
          <h2 className='body'>{newsItem.body}</h2>
          <img className='img' src={newsItem.image} alt={newsItem.title} />
        </div>
      ))}
    </div>
  );
};

export default ServerData;

3. Integrating the Component

Replace the contents of App.js with:

import React from 'react';
import ServerData from './ServerData';

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

export default App;

4. Running the Application

Start the development server:

npm start

Open your browser to http://localhost:3000 to view the application.

Reflecting on the Solution

Through this exercise, we've learned to: