Answer the question
In order to leave comments, you need to log in
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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question