Home > Enterprise >  How to display all items from Firestore in Svelte?
How to display all items from Firestore in Svelte?

Time:12-09

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

CodePudding user response:

You have an array. querySnapshot.docs is an array of query results (docs).

{#each querySnaphot.docs as doc}
  <li>{doc.id} => {doc.data().name}</li>
{/each}

or

{#each querySnaphot.docs as doc}
  {@const {name} = doc.data()}
  <li>{doc.id} => {name}</li>
{/each}

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:

const getQuerySnapshot = async () => {
  return await getDocs(collection(db, "users"));
}

let promise = getQuerySnapshot ();

The getQuerySnapshot arrow function returns a promise. More here.
To resolve the promise you can:

{#await promise then guerySnapshot}
  {#each guerySnapshot.docs as doc}
    <li>{doc.id} => {doc.data().name}</li>
  {/each}
{/await}
  • Related