'Warning: Encountered two children with the same key for react infinite scroll
I am making an infinite scroll component using React's IntersectObserver. It's working great, except for the error: Warning: Encountered two children with the same key
{allDogs?.map((dog) => (
<Fragment key={dog?.adopterAttribute?.id}>
{content here}
</Fragment>
In my useEffect hook I set the dog list this way:
setAllDogs((previousDogList) => [
...(previousDogList ?? []),
...newDogs,
]);
I have found this question in stack overflow, but most of the solutions talk about how setState is async, so use a function call which I am already doing. Another mentions using index for the key, but I read elsewhere that that is an anti-pattern. How else could I go about solving this?
Solution 1:[1]
First what I did was to change the key to a template string.
key={`${dog?.adopterAttribute?.id} + ${index}`}
Then once the errors/warnings were gone, I could see the final allDogs data that was coming through, and realized there were some duplicates afterall, meaning that the error was triggered correctly.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | stonerose036 |
