Twirlman
Twirlman

Reputation: 1189

How to check if the directory is not empty and contains and image in React using custom hooks

I'm working on a custom hook for checking directories of specific markets and I want to check if there's an existing image inside. If there is then import the image if not then return a default. This is my code so far without returning the default image.

import { useState, useEffect } from 'react';
import { brand, country } from '../resources';
    
const useImgFromDir = (fileName: string) => {
  const [image, setImage] = useState<string>('');

  useEffect(() => {
    const importFile = async () => {
      try {
        const image = await import(`../dir/images/${brand}/${country}/${fileName}.png`);
        // I'm not sure how to use the condition here
        // For now the code is working on not empty directory
        setImage(image.default);
      } catch {
        setImage('');
      }
    };

    importFile();
  }, [brand, country, fileName]);

  return image ?? '';
};

export default useImgFromDir;

Upvotes: 1

Views: 40

Answers (1)

NIKUNJ KOTHIYA
NIKUNJ KOTHIYA

Reputation: 2165

I think you only need to add default image path if image is not available inside directory.

For that you only need to add default image path inside catch block for set image.

useEffect(() => {
    const importFile = async () => {
        try {
            const image = await import(`../dir/images/${brand}/${country}/${fileName}.png`);
            setImage(image.default);
        } catch {
            setImage('path/to/default/image.png');
        }
    };

    importFile();
}, [brand, country, fileName]);

Upvotes: 1

Related Questions