Created
August 23, 2020 08:49
-
-
Save fredriccliver/49da2c44c72506ef018923437a88fcee to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var firebaseConfig = { | |
// ... | |
} | |
// Initialize Firebase | |
firebase.initializeApp(firebaseConfig) | |
const db = firebase.firestore() | |
// adding function (UI) | |
const list = document.querySelector("ul") | |
const addRecipe = (recipe, id) => { | |
const recipeObj = recipe.data() | |
let html = ` | |
<li data-id="${id}"> | |
<div>${recipeObj.name}</div> | |
<button class="btn btn-danger btn-sm my-2">delete</button> | |
</li> | |
` | |
list.innerHTML += html | |
} | |
// deleting function (UI) | |
const deleteRecipe = (id) => { | |
const recipes = document.querySelectorAll("li") | |
recipes.forEach((recipe) => { | |
if (recipe.getAttribute("data-id") === id) { | |
recipe.remove() | |
} | |
}) | |
} | |
// add update handler | |
db.collection("recipes").onSnapshot((snapshot) => { | |
snapshot.docChanges().forEach((changes) => { | |
if (changes.type === "added") { | |
addRecipe(changes.doc, changes.doc.id) | |
} else if (changes.type === "removed") { | |
deleteRecipe(changes.doc.id) | |
} | |
}) | |
}) | |
// add button | |
const form = document.querySelector("form") | |
form.addEventListener("submit", (event) => { | |
event.preventDefault() | |
const now = new Date() | |
const recipe = { | |
name: form.recipe.value, | |
created_at: firebase.firestore.Timestamp.fromDate(now), | |
} | |
db.collection("recipes") | |
.add(recipe) | |
.then(() => { | |
console.log("recipe added") | |
}) | |
.catch((err) => console.log(err)) | |
}) | |
// delete button | |
list.addEventListener("click", (e) => { | |
// console.log(e) | |
if (e.target.tagName === "BUTTON") { | |
const id = e.target.parentElement.getAttribute("data-id") | |
db.collection("recipes") | |
.doc(id) | |
.delete() | |
.then(() => { | |
console.log(`deleted`) | |
}) | |
.catch((err) => console.log(err)) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment