0

I'm trying myself in react and trying to make a simple application, which will display articles from the Hacker News. I have already made the first call to their API

 componentDidMount() {
    fetch('https://hacker-news.firebaseio.com/v0/jobstories.json?print=pretty')
        .then(res => res.json())
        .then(articles => {
            this.setState({articles})
        })
  }

As the response, it returns an array of the articles IDs. To get detailed information for every single article I need to iterate the array I get and to make a second request for every article ID which has to look like

fetch(`https://hacker-news.firebaseio.com/v0/item/{id_from_the_array}`)

And I faced the problem because I have no idea how to implement it in a correct way.. Could someone please advice me?

3
  • Just a for loop? Or even better a foreach loop Commented Apr 24, 2018 at 11:50
  • Could you show a bit more of your errored code? For now on it looks like a typo error in your second fetch (...item/${id... with a $) Commented Apr 24, 2018 at 11:56
  • As for now my code looks like constructor() { super(); this.state = { articles: null } } componentDidMount() { fetch('https://hacker-news.firebaseio.com/v0/askstories.json?print=pretty') .then(res => res.json()) .then(articles => { this.setState({articles}) }) } Commented Apr 24, 2018 at 11:58

2 Answers 2

1

this will help you

import React from "react";
import { render } from "react-dom";
import Hello from "./Hello";


class App extends React.Component {
  state = {
    articles: []
  };

  componentDidMount() {
    fetch("https://hacker-news.firebaseio.com/v0/jobstories.json?print=pretty")
      .then(res => res.json())
      .then(articles => {
        articles.map(item => {
          fetch(`https://hacker-news.firebaseio.com/v0/item/${item}.json?print=pretty`)
            .then(res => res.json())
            .then(detailArticles => {
              const articles = this.state.articles.concat(detailArticles);
              this.setState({ articles });
              });
        });
      });
  }

  render() {
    return <p>{JSON.stringify(this.state.articles) }</p>;
  }
}

render(<App />, document.getElementById("root"));

codesandbox

Sign up to request clarification or add additional context in comments.

Comments

0

One way you can do is like using pagenation or infinite scroll so you can show some 10 or 15 news on the screen and load the next set of data on click of a button. Else you can show only id's on screen and fetch the data on click of a button.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.