How to use "if" inside useState prevState map

Viewed 145

Does anybody know how can i use if statement like this. This example doesnt work

uppy.on('complete', (result) => {
  result.successful.forEach((file) =>
    setImgs((prevState) =>
      prevState.map((item) => {
        if(item.id === file.id) {
          return {
            ...item,
            image: file.preview
          }
        }
      })
    )
  )
})
    

And this works, but there s no if

uppy.on('complete', (result) => {
  result.successful.forEach((file) =>
    setImgs((prevState) =>
      prevState.map((item) => ({
        ...item,
        image: file.preview,
      }))
    )
  )
})
3 Answers

I don't think you need to map if you're just trying to find an item. You could do

const item = prevState.find(x.id ==> file.id)
return item? {...item.image:file.preview} : null

"doesn't work" will need more specification. Out of observation I can tell that it needed to have else statement or without, in order to return item if no change is required. The variable - item is unchanged element of imgs array, which we put back.
This is after refactoring your pseudocode:

uppy.on("complete", (result) => {
  result.successful.forEach((file) => 
    setImgs((prevState) =>
      prevState.map((item) => {
        if (item.id === file.id) {
          return { id: item.id, image: file.preview };
        } else return item;
      })
    )
  );
});

Check the sandbox here

Since you are using a map that returns a new array, also you are trying to add an image key to the matched item only then, you need to also return for the else case.

const data = state.map((item) => {
  if (item.id === file.id) return { ...item, image: file.preview };
  return item;
});
Related