Issue
I am trying to create a chatbox with React using typescript and Firebase. This is my code for the Room and Message component:
function ChatRoom() {
const messagesRef = firestore.collection('messages');
const query = messagesRef.orderBy('createdAt').limit(25);
const [messages] = useCollectionData(query, { idField: 'id' });
console.log(messages);
return (
<>
{messages &&
messages.map(msg => <ChatMessage key={msg.id} message={msg} />)}
</>
);
}
function ChatMessage(props: any) {
const { text, uid, photoURL } = props.message;
return (
<>
<p>{text}</p>
</>
);
}
when I specify key={msg.id}
it says that Object is of type 'unknown'. TS2571
. I tried to create an interface for the Mesaage which is:
interface Message {
id: string;
text: string;
createdAt: { nanoseconds: number; seconds: number };
}
But I'm not able to understand how do I specify this Interface to the msg
in the map function.
I tried:
{messages && messages.map(msg: Message => <ChatMessage key={msg.id} message={msg} />)}
but that didn't work too. I am new to TypeScript and React and any help would be appreciated. Much thanks.
Solution
Use your interface and type assertion whithin your map function
messages.map(msg => key = {(msg as ChatMessage).id} message = {msg})
Answered By - ricardo-dlc
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.