Grande amore
Grande amore

Reputation: 37

How to append files in another object ReactJS?

I have an array of files for appending them in form data later, but first i need to compress them and append in new array of already compressed files. I'm stuck with appending files to new array in loop.

What i did tried:

const [compressedImages, setCompressedImages] = useState([]);

In loop:

setCompressedImages(...compressed) //it doesn't seem to work

one more try: (in loop)

compressedImages = [...compressed] //doesn't work

OR

compressedImages.push(compressed) //doesn't work

Why spread operator doesn't work in that case ?

What do I have

<input
       type="file"
       multiple
       onChange={e => selectImages(e)}
  />

Function selectImages:

const [images , setImages] = useState([]);
const selectImages = e => {
        setImages(e.target.files);
    }

Then I need to compress my files and append them all in another array.

for (let i = 0; i<images.length; i++){
            let compressed = await imageCompression(images[i], options)
            images = [...compressed]
            //at the end of the loop I must have exactly the same array as 'images' 
            //but with already processed files
        }

Upvotes: 0

Views: 670

Answers (1)

Navid Naseri
Navid Naseri

Reputation: 134

To add an element to an array state, you should create a new array based on current state and add the new element to it, then set the new array as state:

const [myState, setMyState] = useState([]);
// Add an element to state(long way)
myState.push('element');
setMyState(myState);
// Add an element to state(short way)
setMyState([...myState, 'element']);

Upvotes: 1

Related Questions