I put the key prop everywhere they are needed:
- lists
- map functions
but the error is still occurring, as you can see it says that error is occurring in method of "Rendered Route" I’m not sure what kind of component is that maybe it’s a component from React-Router but this error is occurring only on my index page nowhere else…
I can’t find the issue anywhere even in the index page, every list items has it’s own key prop and Layout page look like this:
const Layout: FC = () => {
const { data } = useQuery<response>(
"authData",
{
queryFn: () => axios.get(`/api/auth/user`),
retry: false,
refetchOnWindowFocus: false
}
)
if (data) {
console.log(data);
return (
<>
<UserContext.Provider value={data.data}>
<Navbar/>
<Outlet />
</UserContext.Provider>
</>
);
}
return (
<>
<Navbar/>
<Outlet />
</>
);
};
This is a index page where the error is probably occurring not sure why.
export const Index = () => {
const { fetchNextPage, hasNextPage, data, refetch, error } = useInfiniteQuery(['posts'], ({ pageParam = '' }) => fetchPosts({ pageParam }), {
getNextPageParam: (lastPage, allPages) => lastPage.nextId ?? false,
})
const { inView, ref } = useInView()
useEffect(() => {
if (inView && hasNextPage) {
fetchNextPage()
}
}, [inView, hasNextPage])
const user = useContext(UserContext);
if (data && data?.pages[0].posts.length > 0) {
return (
<main className="flex p-1 md:p-4 mr-auto ml-auto max-w-[750px] lg:col-start-2">
<section className="flex flex-col gap-2 pt-12 w-full ">
{data.pages.flatMap((page, i) => {
return (
<ul className="flex flex-col gap-2" key={i}>
{page.posts.map((ele) => {
return
<li key={ele.id}>
<PostCard
key={ele.id}
cardType=""
likedBy={ele.likedBy}
liked={ele.likedBy.some((e) => {
return e.id == user.id
})}
author={ele.author}
comments={ele._count.comments > 0
? ele._count.comments
: 0
}
community={ele.community}
refetch={refetch}
content={ele.content}
id={ele.id}
likeCount={ele._count.likedBy}
title={ele.title}
type={ele.type}
/>
</li>
})}
</ul>
)
})}
<div
className="mx-auto flex max-w-6xl justify-center opacity-0"
ref={ref}
/>
</section>
</main>
);
}
2
Answers
I think each key given to child elements should be unique. Returned in map function
I’d suggest you prefix
key
values with where you use them, e.g.This makes sure you’re not reusing the same
key
somewhere else on the same page to ensure it’s unique in the whole app (could happen that the id is used in two different loops I guess).I can’t exactly see where you add the routes (navigation) but there also you should make sure the ke is really unique, either you forgot to set a
key
there or it’s not unique…Aren’t you using
<Route />
somewhere to dynamically create routes? Probably there you messed up thekey
attribute.To wildly guess check inside
<Navbar />
, feels like there your Nav links are generated…?