Home > Back-end >  setState in the map only the last loop is stored in the state
setState in the map only the last loop is stored in the state

Time:10-07

I'm trying to save an object into a state using setState inside a map loop, but I'm only getting the last data stored in the state. my code is like this:

acceptedFiles.map((fileImg) => {
  setImages([
    ...images,
    {
      rand_id: Math.floor(Math.random() * 1000   1),
      image_file: fileImg,
    },
  ]);
});

for example, suppose "acceptedFiles" has 5 data, then only the last data entered or stored in the state image.

Previously I had searched on stackoverflow according to the title of my problem, so I wrote this question.

For all suggestions for my problem, I thank you in advance.

CodePudding user response:

images is the same every time through the loop, so you keep starting from scratch and adding a single image. Whichever setState you do last is the one that sticks. If you must repeatedly call setImages, then make sure you're always starting from the latest state, by doing the function version of set state:

acceptedFiles.forEach((fileImg) => {
  setImages(prev => [
    ...prev,
    {
      rand_id: Math.floor(Math.random() * 1000   1),
      image_file: fileImg
    },
  ]
})

However, in your case, why not just set state once?

const newFiles = acceptedFiles.map((fileImg) => ({
  rand_id: Math.floor(Math.random() * 1000   1),
  image_file: fileImg,
});
setImages(prev => [
  ...prev,
  ...newImages,
]);
  • Related