I've made a copy of the Hacker News Search but I can't display all stories from the API when I get on my website. No stories appear at all. I have to type something on the searchbar to display them all.
I've fetched the data with axios, I console.log
the collection and it appears that the data has been successfully fetched because I can see the collection on my console.
The github repo : https://github.com/vnsteven/hacker-news-react
The website : https://vnsteven.github.io/hacker-news-react/
The beginning of my App.js file (src/containers/App.js):
import React, { Component } from 'react';
import Navbar from '../components/Navbar/Navbar';
import Footer from '../components/Footer/Footer';
import Items from '../components/Items/Items';
import './App.css';
import axios from './axios-hn.js';
class App extends Component {
state = {
list: [],
initialList: [],
favoriteList: [],
count: 0,
favoriteCount: 0
};
async componentDidMount() {
try {
const fetchingData = await axios.get('topstories.json');
const itemIds = await fetchingData.data;
const list = [];
itemIds.forEach((id) => {
axios.get(`item/${id}.json`).then((res) =>
list.push({
id: res.data.id,
title: res.data.title,
score: res.data.score,
url: res.data.url,
author: res.data.by
})
);
});
this.setState({ initialList: list });
} catch (err) {
console.error(err);
}
}
Here is an example of how you can use the "HackerNews API":
First, the TopStories
endpoint returns a list of post ids
. You then need to resolve each id
into its own post
. To simplify that, you can take advantage of the Promise.all
API. This method resolves when all the promises
provided in an input array, resolve themselves.
I am also using "React Hooks" to handle state changes. Take a look at how to handle state using useState
and useEffect
hooks.
Anyways, here is the code example: