0

I have an image input tag which is multiple. I want each image to be scaled down. I use the map function for this. I call this within a useEffect function. But now it is the case that the map function is only run through once, no matter how many images are in an array. How can I change this ?

const articelImg = (e) => {
if (e.target.files && e.target.files.length > 0) {
  setFiles([...files, e.target.files]);
}
};

useEffect(() => {
files.length &&
  files.map(async (file, idx) => { //Two objects, but only interred once
    const thump = await thumpnail(file[idx]);
    setThumpnails([...thumpnails, thump]);
  });
}, [files]);

enter image description here

2 Answers 2

1

when you are working with async/await code in a loop best approach is to use for of loop, below is the code you can give it a try

const articelImg = (e) => {
  if (e.target.files && e.target.files.length > 0) {
    setFiles([...files, e.target.files]);
  }
  };
  
  useEffect(() => {
    (async () => if (files.length) {
      for await (let file of files){
        const thump = await thumpnail(file[idx]);
        setThumpnails([...thumpnails, thump]);
      }
    })()
    
  }, [files]);
Sign up to request clarification or add additional context in comments.

2 Comments

Thx, but dosen't take effect
are you getting any error, or facing issue related to this?
0

You have probably got a stale state in this line setThumpnails([...thumpnails, thump]); because of async settings. Try this one setThumpnails(thumpnails => [...thumpnails, thump]); this will provide you a latest snapshot of state or use refs as described in docs.

Comments

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.