DEV Community

Cover image for Hacker News API & fechting data with React js
MedCode
MedCode

Posted on • Edited on

Hacker News API & fechting data with React js

To fetchdata from the Hacker News API using React.js, you can utilize the fetch function or the axioslibrary. Here's an example using the fetchfunction:

1. Install the axioslibrary (if not already installed):

npm install axios
Enter fullscreen mode Exit fullscreen mode

2. In your React component file, import the necessary dependencies:

import React, { useEffect, useState } from 'react';
import axios from 'axios';
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

In this example, we fetch the top story IDs from the Hacker News API and store them in the newsDatastate 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)