Multiple Images Upload array.concat Doesn't Show First Upload
Unanswered
Baldfaced hornet posted this in #help-forum
Baldfaced hornetOP
Weird one here where if I upload an image the very first image doesn't appear in my array however I can see it on the page... then when I upload a 2nd image that appears as well but now the array says it has 1 file in it.
const handleChangeImage = (e: ChangeEvent<HTMLInputElement>) => {
e.preventDefault();
const checkForUpload = e.target.files?.[0]
if (!checkForUpload) {
return
}
const selectedImageFiles = e.target.files;
console.log(selectedImageFiles)
if (selectedImageFiles.length > 4) {
setErrorTooManyFiles("You can only upload 4 images")
return
} else {
setErrorTooManyFiles("")
}
const selectedImageFilesArray = Array.from(selectedImageFiles);
console.log(selectedImageFilesArray)
const imagesArray = selectedImageFilesArray.map((file) => {
return URL.createObjectURL(file)
});
console.log(selectedImages.length)
console.log(imagesArray.length)
console.log(selectedImages.length + imagesArray.length)
if (selectedImages.length + imagesArray.length < 5) {
setSelectedImages((previousImages) => previousImages.concat(imagesArray));
setSelectedImagesData((previousImagesData) => previousImagesData.concat(selectedImageFilesArray));
setform((prevState) => ({ ...prevState, image: selectedImages}))
}
console.log(selectedImagesData)
};6 Replies
Baldfaced hornetOP
You can see it shows the file exist but then when trying to set the image to the selectedImagesData array it becomes an empty object
However if I add a 2nd image it all of a sudden becomes an object with 1 file inside of it
I figure this is some type of issue in "setSelectedImagesData(( previousImageData ) => previousImagesData.concat(selectedImageFilesArray));" but weirdly the line right above this(which basically does the same thing but with a local URL array to display the picture) works fine and displays the 1st + 2nd pictures
Baldfaced hornetOP
After further testing it would seem as if what is causing this is:
The useState is declared as a normal array
But the first time I attempt to concat to that array with the File[] type it comes back as still a normal array... then the 2nd attempt it's like the useState updates to realize it's suppose to be a File[] and then works.
The useState is declared as a normal array
const [selectedImagesData, setSelectedImagesData] = useState([])But the first time I attempt to concat to that array with the File[] type it comes back as still a normal array... then the 2nd attempt it's like the useState updates to realize it's suppose to be a File[] and then works.
Still working on finding a solution