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

Time:02-03

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;

CodePudding user response:

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]);
  • Related