Home > OS >  display async api request on react js
display async api request on react js

Time:11-01

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));
  }
})();

CodePudding user response:

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>

  • Related