So I would like to fill an array with data from firestore, I'm just unsure how to exactly do it.
I have this accessing the user information and data snapshot of items:
auth.onAuthStateChanged(user => {
if (user) {
db.collection('items').onSnapshot(snapshot => {
setupItems(snapshot.docs);
setupUI(user);
userDetails(user);
}, err =>{
console.log(err.message);
})
} else {
setupUI();
setupItems([]);
userDetails();
}
});
This works in another part of my project to fill in template literals with details from my 'items' collection and also allows me to access the current users UID and their specific document within the users collection.
I currently have this hardcoded:
const products = [
{
id: 1,
img: './cod.jpeg',
name: 'Call of Duty',
price: 3,
cart: false,
quantity: 1,
total: 0
},
{
id: 2,
img: './fonv.jpeg',
name: 'Fallout:New Vegas',
price: 4,
cart: false,
quantity: 1,
total: 0
},
{
id: 3,
img: './ror2.jpeg',
name: 'Risk of Rain 2',
price: 5,
cart: false,
quantity: 1,
total: 0
}
];
I also have the exact same fields in my items collection in firestore i.e. document A has a string field name with apple, string field img with a url, integer field price with a number etc.
Is there a way to make it that for example:
const products = [
{
id: filled by firebase,
img: filled by firebase,
name: filled by firebase,
price: filled by firebase,
cart: false,
quantity: 1,
total: 0
}
I know I'd tack on a foreach loop vs coding each item but I'm unsure how to assign the fields vs hardcoding.
EDIT
Upon adding this:
const itemsx = (data) => {
if (data.length) {
data.forEach(doc => {
const item = doc.data();
products = [
{
id: item.uid,
img: item.artwork,
name: item.gamename,
price: item.price,
cart: false,
quantity: 1,
total: 0
}
];
console.log(products)
});
} else {
console.log('If you see this, preschoolers are more competent than you at this point.');
}
}
I get the correct outputs in the console, however, products[] becomes trapped within itemsx and isn't globally accessible anymore. (I added itemsx(snapshot.docs) to the onAuthStateChange method)
I'm doing something horribly wrong, I know I'm doing something horribly wrong, I'm one step forward but now stuck, can anyone see something I can't.