DEV Community

Retry loading an iframe until reachable in React

fbcyborg on July 25, 2023

Hello everyone, I am trying to implement an Iframe custom component which is loading a web page inside. Sometimes, the web page is not available ...
Collapse
 
fbcyborg profile image
fbcyborg

Hello everyone,

I changed a bit the component in the first post and I think it is okay now:

import React, { useState, useEffect } from "react";

export const CustomIFrame = (props) => {
  const [status, setStatus] = useState("");
  const [error, setError] = useState(null);
  const CHECK_INTERVAL = 10000;

  useEffect(() => {
    const fetchData = async () => {
      console.log(
        "Periodic check in progress - " + new Date() + " - Status: " + status
      );
      try {
        if (!status || status !== 200) {
          console.log("No data yet: fetching...");
          const res = await fetch(props.url);
          const response = res ? res : undefined;
          const newStatus = response && response.status ? response.status : "";
          console.log("newStatus: " + newStatus);
          setStatus(newStatus);
        }
      } catch (err) {
        console.error(err);
        setError(err.message);
      }
    };

    const interval = setInterval(fetchData, CHECK_INTERVAL); // Initial data fetching

    // Clean up the interval if the component unmounts
    return () => {
      clearInterval(interval);
      clearTimeout(fetchData);
    };
  }, [status, props.url]);

  return (
    <div>
      {status === 200 ? (
        <div>
          <iframe
            title="my iframe"
            id="myIframe"
            height="768"
            width="1366"
            src={props.url}
          />
        </div>
      ) : error ? (
        <div>Error: {error}</div>
      ) : (
        <div>Loading...</div>
      )}
    </div>
  );
};

Enter fullscreen mode Exit fullscreen mode

I'm not 100% about the solution I have found, but I hope someone can give me a feedback on that.