I understand the issue here being that each child in a list requires a unique key but I am doing that and it still is not working. Could anyone give me any tips why please? If you could please look at the line with the asterisks, that is the line where I have added my key and yet I still get this warning. Thank you in advance.
"use client";
import {auth} from "../../../utils/firebase";
import {useAuthState} from "react-firebase-hooks/auth";
import {useRouter} from "next/navigation";
import Message from "../components/message";
import { useEffect, useState } from "react";
import { collection, deleteDoc, doc, onSnapshot, query, where} from "firebase/firestore";
import {db} from "../../../utils/firebase";
import {BsTrash2Fill} from 'react-icons/bs';
import {AiFillEdit} from 'react-icons/ai';
import Link from "next/link";
export default function Dashboard(){
const route = useRouter();
const [user,loading] = useAuthState(auth);
const [posts, setPosts] = useState([]);
//See if user is logged in
console.log(user);
const getData = async () => {
if(loading) return;
if (!user) return route.push('/auth/login');
const collectionRef = collection(db, "posts");
const q = query(collectionRef, where("user", "==", user.uid));
const unsubscribe = onSnapshot(q, (snapshot) => {
setPosts(snapshot.docs.map((doc)=> ({...doc.data(), id: doc.id})));
});
return unsubscribe;
}
//Delete Post
const deletePost = async(id) => {
const docRef = doc(db, "posts", id)
await deleteDoc(docRef);
}
//Get users data
useEffect(()=>{
getData();
},[user,loading]);
return(
<div>
<h1>Your Posts</h1>
**<div>
{posts.map((post)=>{
return (<Message{...post} key ={post.id}> <div className="flex gap-4">**
<button onClick = {()=> deletePost(post.id)}className="text-pink-600 flex items-center justify-center gap-2 py-2 text-sm "><BsTrash2Fill className="text-2xl "/>Delete</button>
<Link href = {{pathname: "/post", query: post}}><button className="text-teal -600 flex items-center justify-center gap-2 py-2 text-sm "><AiFillEdit className="text-2xl "/>Edit</button> </Link>
</div> </Message>
);
})}
</div>
<button className= "font-medium text-white bg-gray-800 py-2 px-4 my-6 "onClick={()=> auth.signOut()}>Sign Out</button>
</div>
);
};
2
Answers
I was able to fix this by adding the key prop before the spread operator. Such as:
instead of
There is more information on this solution over here: https://github.com/vercel/next.js/issues/55642
There may be one or more duplicate id’s in your
posts
array which causes this error message.Optionally, you can use array items’ indexes as
key
s while usingmap
function:Even if this solution works for you, don’t forget to check your posts array for duplicate id’s.