score:0

this answer is inspired by this article

const [words, setwords] = react.usestate();

const callapitentimes = async () => {
  // create an array of promises
  let promises = [];
  for (let i = 0; i < 10; i++) {
    promises.push(fetch("https://palabras-aleatorias-public-api.herokuapp.com/random"));
  }

  // wait for all promises to fulfill
  promise.all(promises)
    .then((responses) =>
      // get a json object from each of the responses
      promise.all(responses.map((res) => res.json()))
    )
    .then((data) => {
      // get all the data and store it in our usestate
      const results = data.map(({ body }) => body.word);
      setwords(results);
    })
    .catch((err) => console.warn(err));

};

// on first render when words === undefined, call api once to fetch first 10 words
useeffect(() => {
  if (!words) {
    callapitentimes();
  }
}, [words]);

return (
  <>
    {/* render each word in the word array */}
    {words.map((word) => (
      <p>{word}</p>
    ))}
    {/* get new words after a button click */}
    <button onclick={() => callapitentimes()}>get new words</button>
  </>
)

Related Query

More Query from same tag