To fetch
data from the Hacker News API using React.js, you can utilize the fetch function or the axios
library. Here's an example using the fetch
function:
1. Install the axios
library (if not already installed):
npm install axios
2. In your React component file, import the necessary dependencies:
import React, { useEffect, useState } from 'react';
import axios from 'axios';
3. Create a component and define a state variable to store the fetched data:
const HackerNews = () => {
const [newsData, setNewsData] = useState([]);
useEffect(() => {
fetchNewsData();
}, []);
const fetchNewsData = async () => {
try {
const response = await axios.get('https://hacker-news.firebaseio.com/v0/topstories.json');
const data = response.data.slice(0, 5); // Fetching top 5 stories
setNewsData(data);
} catch (error) {
console.error('Error fetching Hacker News data:', error);
}
};
return (
<div>
<h1>Hacker News Top Stories</h1>
<ul>
{newsData.map((storyId) => (
<li key={storyId}>{storyId}</li>
))}
</ul>
</div>
);
};
export default HackerNews;
4. Render the component wherever desired in your application:
import React from 'react';
import HackerNews from './HackerNews';
const App = () => {
return (
<div>
<h1>My App</h1>
<HackerNews />
</div>
);
};
export default App;
In this example, we fetch the top story IDs from the Hacker News API and store them in the newsData
state variable. We then render the top story IDs as list items in the component. You can customize the fetching logic and the way you display the data according to your requirements.
Remember to handle any errors that may occur during the API request and adjust the API endpoint or parameters as needed for different data types (e.g., comments, user data),
you can also see how to fetch data in Next.js 14
Top comments (0)