Ask Question

Re-mount component/reset useState on every mapping

Maybe I'm thinking to complicated, but I just can not get this to work.

I'm mapping boxes which I get out of an API to my Box component:

{boxes.max((box) => (
          <div className="box" key={box.id}>
            <BoxCard
              box={box}
              image={box.image ? box.image.id : undefined}
            />
          </div>
))}

In my BoxCard, I'm fetching the image:

const [imageData, setImageData] = useState<string>();

  if (imageId) {
    useFetchItem<typeof Image>("/image/", imageId, {
      onSuccess: (data) => {
        setImageData(data);
      },
    });
  }

and this is then inserted with src={imageData}.

For the first box with an image, everything works fine, but after that, all boxes with images get assigned the image from the first box with an image.
I've already tried with a key prop, but that did not help.

Is there any way to reset the the state of useState on any mapping iteration? Or any other ways?

ReactTypeScriptNextJS

377 views

Author´s Philip image

Philip

Last edited on

1 Answer available

Best answer

You have to put the logic of the image fetch into a useEffect

useEffect(() => {
    useFetchItem<typeof Image>("/image/", imageId, {
      onSuccess: (data) => {
        setImageData(data);
      },
    });
  }, 
  [imageId]
)

BUT it would much much better if the API where you fetch the boxes delivers the image src upfront… so you don't need to fetch them individually!