G
G
Gagatyn2021-09-09 10:30:30
JavaScript
Gagatyn, 2021-09-09 10:30:30

How to make multiple requests in js?

Hacker news provides its API for news, work, etc.
top stories 500 pieces as ID - https://hacker-news.firebaseio.com/v0/topstories.json
and one news - https://hacker-news.firebaseio.com/v0/item/9130260.json

How to link and output these top news to the console?

My attempt is not successful, confused. The function is expected to simply return a list of news inuseEffect(f(), [])

export async function getStoryIDs() {
  let r = await fetch("https://hacker-news.firebaseio.com/v0/topstories.json");
  r = await r.json();

  return await r;
}

export async function getNews() {
  let arrayIDs = await getStoryIDs();
  let array = [];

  // console.log(arrayNews);
  for (let news in arrayIDs) {
    let r = await fetch(
      `https://hacker-news.firebaseio.com/v0/item/${news}.json`
    );
    r = await r.json();

    // .log(await r);
    array.push(await r);
  }
}

//...
  let [data, setData] = useState([]);

useEffect(() => {
    setData(getNews());
  }, []);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
WapSter, 2021-09-09
@Gagatyn

500 requests are waiting for each other)) You haven't heard about optimization. And can you get one?

A
Alexandroppolus, 2021-09-09
@Alexandroppolus

let [data, setData] = useState([]);
useEffect(() => { setData(getNews()); }, []);

You will have a promise in data.
Still, you should use async / await only after understanding promises and asynchrony in general ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question