0

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
        }

1 Answer 1

1

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']);
Sign up to request clarification or add additional context in comments.

5 Comments

Uncaught (in promise) TypeError: compressed is not iterable
Try rechecking your variable names @Grandeamore
compressedImages setting by using setter setCompressedImages. I guess you meant: if i have: let compressed = await imageCompression(e,options); setCompressedImages([...compressed]) instead of suggested: setCompressedImages([...compressedImages]). But nevertheless it is not iterable
Is compressed an element that you want to add to compressedImages? If so, you can setCompressedImages([...compressedImages, compressed]) @Grandeamore
It is working ! Thanks! I used state.push in loop and put setter after loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.