前提
React, TypeScriptでfirestoreからデータを取得したいのですが、以下のようなエラーが発生しました。
実現したいこと
- firestoreからpostsデータを取得し、map関数でpostを展開
発生している問題・エラーメッセージ
エラーメッセージ (parameter) querySnapshot: QuerySnapshot<DocumentData> ---------------------------------------------------------------------------- 型 'DocumentData[]' の引数を型 'SetStateAction<Posts>' のパラメーターに割り当てることはできません。 型 'DocumentData[]' を型 'Posts' に割り当てることはできません。 型 'DocumentData' には 型 '{ displayName: string; userName: string; text: string; image: string; }' からの次のプロパティがありません: displayName, userName, text, image
該当のソースコード
TypeScript
1import { Box, Heading } from "@chakra-ui/react"; 2import Post from "./PostOne"; 3import TweetBox from "./TweetBox"; 4import { collection, getDocs } from "firebase/firestore"; 5import db from "../../firebase"; 6import { useState } from "react"; 7 8type Posts = { 9 displayName: string; 10 userName: string; 11 text: string; 12 image: string; 13}[]; 14 15const TimeLine = () => { 16 const [posts, setPosts] = useState<Posts>([]); 17 const postsColRef = collection(db, "posts"); 18 getDocs(postsColRef).then((querySnapshot) => { 19 setPosts(querySnapshot.docs.map((doc) => doc.data())); 20 }); 21 22 return ( 23 <Box 24 overflowY="scroll" 25 flex="0.45" 26 borderRight="1px solid #efeff2" 27 css={{ "&::-webkit-scrollbar": { display: "none" } }} 28 > 29 <Box 30 background="white" 31 border="1px solid #efeff2" 32 p="15px 20px" 33 top="0" 34 textAlign="left" 35 position="sticky" 36 > 37 <Heading fontSize="20px" as="h2" fontWeight="bold"> 38 ホーム 39 </Heading> 40 </Box> 41 <TweetBox /> 42 43 {posts.map((post) => ( 44 <Post 45 displayName={post.displayName} 46 userName={post.userName} 47 text={post.text} 48 image={post.image} 49 /> 50 ))} 51 </Box> 52 ); 53}; 54 55export default TimeLine;
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。