Home > other >  React Map function iterates through an array only once
React Map function iterates through an array only once

Time:07-26

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

CodePudding user response:

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]);

CodePudding user response:

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

  • Related