Home > database >  React dropzone. Add files to state instead of overwriting them
React dropzone. Add files to state instead of overwriting them

Time:04-16

Why can't I use setImages like this. I works like this setImages([...images, acceptedFiles[0]) and like this setImages(acceptedFiles). I don't get what the problem is.

const {getRootProps, getInputProps} = useDropzone({
        noClick:true,
        accept: "image/*",
        onDrop: (acceptedFiles) => {
            acceptedFiles.map((file:any, index:number) => Object.assign(file, {
                preview: URL.createObjectURL(file)
            }))
            setImages([...images, acceptedFiles])
        }
    })

CodePudding user response:

you can use previous state value. e.g, setState((prev) => something);

setImages((images) => [...images, acceptedFiles])

CodePudding user response:

I have no clue, why this isn't working and I am hoping for someone to explain that, but it works with setImages(images.concat(acceptedFiles))

  • Related