All files / src/components/ui/image-with-fallback index.tsx

91.66% Statements 33/36
100% Branches 5/5
50% Functions 1/2
91.66% Lines 33/36

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 371x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 81x 81x 81x 43x 43x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x       81x 81x 81x  
'use client';
 
import Image, { ImageProps } from 'next/image';
 
import { useEffect, useState } from 'react';
 
interface ImageWithFallbackProps extends Omit<ImageProps, 'src' | 'onError'> {
  src: string | null;
  fallbackSrc: string;
}
 
export const ImageWithFallback = ({ src, fallbackSrc, ...rest }: ImageWithFallbackProps) => {
  const [error, setError] = useState(false);
 
  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect
    setError(false);
  }, [src]);
 
  const imgSrc = error || !src || src === null ? fallbackSrc : src;
 
  return (
    <Image
      {...rest}
      draggable={false}
      loading='eager'
      quality={100}
      src={imgSrc}
      unoptimized
      onError={(e) => {
        e.preventDefault();
        setError(true);
      }}
    />
  );
};