Reputation: 195
In my database from Firestore, each User has a sub-collection called Apps. I need to add in my state the id of each document and their data. I know how to add the data in my state, with the following code setApps(data.docs.map(doc => doc.data()))
and I know how to get the ID of each document data.docs.map(doc => console.log(doc.id, doc.data()))
.
But how can I add in my state doc.id
and doc.data()
at the same time?
Thanks for your help.
function AppList() {
const [apps, setApps] = React.useState([])
React.useEffect(() => {
const fetchData = async () => {
const db = firebase.firestore()
var user = firebase.auth().currentUser;
if (user != null) {
var uid = user.uid
const data = await db
.collection('Users').doc(uid)
.collection('Apps').get()
//Add the data of each doc in my state
setApps(data.docs.map( doc => doc.data()));
//Get the document ID
data.docs.map(doc =>
console.log(doc.id, '=>', doc.data())
);
}
}
fetchData()
}, [])
return (
<Row gutter={{ xs: 8, sm: 16, md: 24, lg: 32 }}>
{apps.map(app => (
<Col className="gutter-row" span={100}>
<Card
style={{ width: 300, marginTop: 16}}
actions={[
<Button type="default" size='middle'>
<Link to={app.appName}>
<EditOutlined />
<span> Edit the app </span>
</Link>
</Button>,
]}>
<Meta
title= {app.appName}
description={app.description}
/>
</Card>
</Col>
))}
</ Row>
);
}
Upvotes: 4
Views: 2801
Reputation: 1
Besides that, you can add this if you use setState
initialData.forEach((doc) => {
this.setState({
data: [...this.state.data,{...doc.data(), id: doc.id }],
});
});
Upvotes: 0
Reputation: 195
I finally found the solution
setApps(data.docs.map(doc => {return {...doc.data(), id: doc.id} }));
Upvotes: 7