We aim to create a React component that fetches data from the Fortnite API's news endpoint and displays it. This involves:
useEffect hook to perform a side effect (data fetching).To tackle this problem, we'll follow these steps:
ServerData.ServerData, initialize a state variable serverData with its setter function setServerData.useEffect hook to fetch data from the Fortnite API upon component mount.Let's delve into the implementation of the ServerData component.
Ensure you have Node.js installed. Then, set up the project:
npx create-react-app fortnite-news
cd fortnite-news
npm install
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;
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;
Start the development server:
npm start
Open your browser to http://localhost:3000 to view the application.
Through this exercise, we've learned to:
useEffect hook for side effects like data fetching.