Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

display async api request on react js

i have this code that shows the data on console but how can i display the data of all 3 apis at the same time on the page using react app .JSX using .map ?

(async () => {
  try {
    const urls = [
      "https://api.chucknorris.io/jokes/random",
      "https://api.chucknorris.io/jokes/random",
      "https://api.chucknorris.io/jokes/random",
      "https://api.chucknorris.io/jokes/random",
    ];

    const requests = urls.map((url) => fetch(url));
    const responses = await Promise.all(requests);
    const errors = responses.filter((response) => !response.ok);

    if (errors.length > 0) {
      throw errors.map((response) => Error(response.statusText));
    }

    const json = responses.map((response) => response.json());
    const data = await Promise.all(json);

    data.forEach((datum) => console.log(datum));
  }
  catch (errors) {
    errors.forEach((error) => console.error(error));
  }
})();

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can use Promise.All method and save the resolved data to a state and map accordingly to render data …

A sample e.g. below

const { useState, useEffect } = React;

const urls = [
  "https://api.chucknorris.io/jokes/random",
  "https://api.chucknorris.io/jokes/random",
  "https://api.chucknorris.io/jokes/random",
  "https://api.chucknorris.io/jokes/random",
];

const App = () => {
  const [data, setData] = useState();

  useEffect(() => {
    const promises = urls.map((url) =>
      fetch(url)
        .then((res) => res.json())
        .then((data) => data)
    );
    Promise.all(promises).then((values) => {
      setData(values);
    });
  }, []);

  if (!data) return "Loading ..."; // this is not exact way to do a loading state just for illustration ...

  return (
    <div>
      {data.map((item) => (
        <p key={item.id}>{item.value}</p>
      ))}
    </div>
  );
};

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading