I’m following a simple firebase tutorial to get me back into coding. The tutorial taught how to use snapshot. i tried it but it doesn’t seems to work as intended. My intention was for it to actively listen for any changes and change it. Snapshot seems to not be able to do it.
Something like this: https://www.youtube.com/watch?v=rfQ2F8kQEUg&t=65s
Below is my code
index.html
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>learning how to do firebase 9</title>
</head>
<body>
<h1>Add Form</h1>
<form class="add">
<label for="title">Title:</label>
<input type="Text" name="Title" id="title" required>
<label for="author">Author</label>
<input type="Text" name="Author" id="author" required>
<label for="genre">Genre:</label>
<input type="Text" name="Genre" id="genre" required>
<button>Add a new book</button>
</form>
<form class="delete">
<label for="id"> Document id:</label>
<input type="text" name="Id" id="id" required>
<button> delete a book</button>
</form>
<script src="bundle.js"></script>
</body>
</html>
index.js
import {initializeApp} from 'firebase/app'
import {
getFirestore, collection, onSnapshot,
addDoc, deleteDoc, doc
} from 'firebase/firestore'
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
};
// init firebase
initializeApp(firebaseConfig)
//init services
const db = getFirestore()
//collection ref
const colRef = collection(db, 'books')
//real time collection data
onSnapshot(colRef, (snapshot) => {
let books = []
snapshot.docs.forEach((doc) => {
books.push({ ...doc.data(), id: doc.id })
})
console.log(books)
})
//adding documents
const addBookForm = document.querySelector('.add')
addBookForm.addEventListener('submit', (e) =>{
e.preventDefault()
addDoc(colRef, {
Title: addBookForm.Title.value,
Author: addBookForm.Author.value,
Genre: addBookForm.Genre.value
})
.then(() => {
addBookForm.reset()
})
})
//deleting documents
const deletebookform = document.querySelector('.delete')
deletebookform.addEventListener('submit', (e) => {
e.preventDefault()
const docRef = doc(db, 'books', deletebookform.id.value)
deleteDoc(docRef)
.then(() =>{
deletebookform.reset()
})
})
What seems to be the issue. have been trying to debug myself for the past 1-2 weeks