A
A
Alexander2021-05-11 13:34:36
React
Alexander, 2021-05-11 13:34:36

How to make validation for adding images to useState?

How can I implement validation for adding images to useState?
I did some validation on adding images (maximum 4), but it is easy to bypass it by adding 3 or fewer images first and then some more, that is, it only works when the user selects more than 4 images for the first time, but after making two attempts he this validation can be bypassed. I will be grateful for help

export interface ImageObj {
  blobUrl: string
  file: File
}
 const onSelectImage = React.useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files
    if (files) {
      const imgArray: Array<File> = Array.from(files)

      if (imgArray.length <= 4) {
        const newState = imgArray.map((file: File) => ({
          blobUrl: URL.createObjectURL(new Blob([file])),
          file,
        }))
        setImages((prev: ImageObj[]): Array<ImageObj> => [...prev, ...newState])
      } else {
        enqueueSnackbar('Max 4 photos.', {
          variant: 'info',
        })
      }
    }
  }, [])

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Egor Zhivagin, 2021-05-11
@Krasnodar_etc

if ((prev.length + imgArray.length) <= 4)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question