Im trying to make a To-do app. I can get all the information from firebase in the console, however the only item I can get to display in the ui is the last one. How can i display all of them?
let msg
let textinput
async function f() {
try {
const docRef = await addDoc(collection(db, "users"), {
name: textinput,
});
console.log("Document written with ID: ", docRef.id);
} catch (e) {
console.error("Error adding document: ", e);
}}
onMount(async () => {
const querySnapshot = await getDocs(collection(db, "users"));
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
msg = doc.data().name
console.log(doc.id, " => ", doc.data());
});
});
<h1>
this is for datebase
</h1>
<input type="text" bind:value={textinput}>
<p>{msg}</p>
ui and the console
console_output
I tried {#each querySnaphot as doc}, but querySnapshot is not defined
2
Answers
You have an array. querySnapshot.docs is an array of query results (docs).
or
Bonus looping:
If you have an object you can loop:
{#each Object.keys(obj) as key}
or:
{#each Object.entries(obj) as [key, value]}
Update querySnapshot:
The getQuerySnapshot arrow function returns a promise. More here.
To resolve the promise you can:
You might be interested in sveltefire as it avoids a lot of the redundant boilerplate around using firebase and really cleans up svlete code.
You can easily use sveltefire realtime components which automagically get data and subscribe to realtime changes making your data reactive right out of the box
It is however useful to learn how firestore works in the first place, but this is a really fun and fast way to work with firebase and svelte