1

I am trying to build something with hacker news API but I have a problem though. To get the items displayed to the screen. The items I need I need to first call another endpoint. I called this endpoint and looped through it so I can pass the data from that endpoint to the items endpoint which I need to work but I am only getting one Item displayed. How can I further do this to get like 30 items all at once?

state={
    hackernews: []
  }
  componentDidMount(){
    Axios.get('/newstories.json')
    .then(res => {
      for(let i = 0; i<res.data.length; i++){
        const newsID = res.data[i];
        return Axios.get(`/item/${newsID}.json`)
      }
    })
    .then(res=>{
      const news = res.data
      this.setState({hackernews: [...this.state.hackernews, news]})
      
    })
  }

The hackernews api link https://github.com/HackerNews/API

1 Answer 1

1

You could use async/await to fetch the IDs, then use .then normally :

 async componentDidMount(){
   let res=await Axios.get('/newstories.json')

     for(let i = 0; i<res.data.length; i++){
        const newsID = res.data[i];
       Axios.get(`/item/${newsID}.json`)  
       .then(res1=>{
          const news = res1.data
          this.setState({hackernews: [...this.state.hackernews, news]})
      
         })
     }

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

3 Comments

Thank you so much. However, there's a problem though. It comes onto the screen but throws an error.
It continues looping through the items until it throws an error of null for what I am trying to do. I have used the params method to limit it but it still throws it. I would look for more information online.
if there's a lot of details you could post another question

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.