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

92.1% Statements 35/38
100% Branches 5/5
50% Functions 1/2
92.1% Lines 35/38

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 37 38 391x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 81x 81x 81x 81x 81x 81x 81x 50x 50x 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;
  fallbackSrc?: string;
}
 
import { DEFAULT_PROFILE_IMAGE } from 'constants/default-images';
 
export const ImageWithFallback = ({
  src,
  fallbackSrc = DEFAULT_PROFILE_IMAGE,
  ...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}
      src={imgSrc}
      onError={(e) => {
        e.preventDefault();
        setError(true);
      }}
    />
  );
};