|
| 1 | +import React, { useState, useEffect } from "react"; |
| 2 | +import { DotLottieReact } from "@lottiefiles/dotlottie-react"; |
| 3 | +import Loader from "./Loader"; |
| 4 | + |
| 5 | +const LottieWithLoader = ({ |
| 6 | + src = "https://lottie.host/00a72a09-f2d4-493a-9b2d-2843bf067638/Ic7jJ44wLJ.json", |
| 7 | + minLoaderTime = 1000, |
| 8 | + timeout = 10000 |
| 9 | +}) => { |
| 10 | + const [isLoaded, setIsLoaded] = useState(false); |
| 11 | + const [hasError, setHasError] = useState(false); |
| 12 | + const [animationSrc, setAnimationSrc] = useState(null); |
| 13 | + |
| 14 | + useEffect(() => { |
| 15 | + const timer = setTimeout(() => { |
| 16 | + setHasError(true); |
| 17 | + }, timeout); |
| 18 | + |
| 19 | + fetch(src) |
| 20 | + .then((response) => { |
| 21 | + if (!response.ok) { |
| 22 | + throw new Error("Network response was not ok"); |
| 23 | + } |
| 24 | + return response.blob(); |
| 25 | + }) |
| 26 | + .then((blob) => { |
| 27 | + const objectURL = URL.createObjectURL(blob); |
| 28 | + setAnimationSrc(objectURL); |
| 29 | + setTimeout(() => { |
| 30 | + setIsLoaded(true); |
| 31 | + }, minLoaderTime); |
| 32 | + }) |
| 33 | + .catch((error) => { |
| 34 | + console.error("There was a problem with the fetch operation:", error); |
| 35 | + setHasError(true); |
| 36 | + }); |
| 37 | + |
| 38 | + return () => clearTimeout(timer); |
| 39 | + }, [src, minLoaderTime, timeout]); |
| 40 | + |
| 41 | + return ( |
| 42 | + <div> |
| 43 | + {!isLoaded && !hasError && ( |
| 44 | + <div className="loader"> |
| 45 | + {" "} |
| 46 | + <Loader /> |
| 47 | + </div> |
| 48 | + )} |
| 49 | + {hasError && <div className="error">Failed to load animation</div>} |
| 50 | + {isLoaded && animationSrc && ( |
| 51 | + <DotLottieReact |
| 52 | + src={animationSrc} |
| 53 | + loop |
| 54 | + autoplay |
| 55 | + style={{ display: "block" }} |
| 56 | + /> |
| 57 | + )} |
| 58 | + </div> |
| 59 | + ); |
| 60 | +}; |
| 61 | + |
| 62 | +export default LottieWithLoader; |
0 commit comments