DEV Community

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

Posted on • Edited on

1

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

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs