const Home = () => {
const postsCollectionRef = collection(db, "data");
const postListArray = []
useEffect(() => {
const getPosts = async () => {
const data = await getDocs(postsCollectionRef);
data.forEach((doc) => {
const post = { ...doc.data() }
postListArray.push(post)
});
};
getPosts();
console.log(postListArray.data);
}, []);
return (
<div>test</div>
);
};
I was unable to consume the data i fetched from firestore. Attached with my data structure.
First, from the console log
console.log(postListArray);
it return the array successfully
Then, i tried to
console.log(postListArray.length);
it returned 0 (i believed it was 1, please point out my misunderstanding)
Then, i tried the code above
console.log(postListArray.data);
it returned undefined
Then, i tried to push my luck
console.log(postListArray.data.Example);
i believe it's type error
How can I access data inside the return object (if it had returned or not)?
data structure
some attempts on console log
type error?
CodePudding user response:
First, I see you're storing your list of posts as a const
in your component, you should use some state to keep track of that, something along the lines of
const [postList, setPostList] = useState([]);
useEffect(() => {
const getPosts = async () => {
const data = await getDocs(postsCollectionRef);
data.forEach((doc) => {
const post = { ...doc.data() };
setPostsList(prev => [...prev, post]);
});
});
Second, console.log(postListArray.data);
won't work because postListArray
is an array, and there is no data
attribute on the Array type - You can take a look at the MDN documentation for the Array data type and it's attributes.
Your postList
will look like this:
postList: [
{
data: {...}
},
{
data: {...}
}
]
So you need to access each element in the array and get it's data
attribute. Like this:
postList.forEach(post => {
console.log(post.data)
});
Then you can consume your list of posts by rendering it in your JSX if you map postList
to an array of HTML elements like so:
return (
<div>
{
postList.map((post, index) => <span key={index}>{post.data}</span>)
}
</div>
)
CodePudding user response:
Since getPosts
is an async
function you need to use await
or then
when calling it. For example:
getPosts().then(() => {
console.log(postListArray);
})
Without then()
(or await
) the console.log
runs before the getPosts
call completed, and thus before your array is populated.