Advertisement
didkoslawow

Untitled

Apr 19th, 2023
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.19.1/firebase-app.js';
  2. import { getDatabase, ref, push, onValue, remove } from 'https://www.gstatic.com/firebasejs/9.19.1/firebase-database.js';
  3.  
  4. // DON'T FORGET TO CHANGE SEQURITY SETTINGS IN DATABASE LATER !!!
  5.  
  6. const appSettings = {
  7.   databaseURL: 'https://listme-5291d-default-rtdb.europe-west1.firebasedatabase.app/',
  8. };
  9.  
  10. const app = initializeApp(appSettings);
  11. const database = getDatabase(app);
  12. const productsInDB = ref(database, 'products');
  13.  
  14. const addProductBtn = document.getElementById('add-btn');
  15. const ulElement = document.getElementById('product-list');
  16. const inputElement = document.getElementById('input-field');
  17. addProductBtn.addEventListener('click', onAddProduct);
  18.  
  19. onValue(productsInDB, loadProducts);
  20.  
  21. function onAddProduct() {
  22.   const input = inputElement.value;
  23.  
  24.   if (!isEmptyString(input)) {
  25.     push(productsInDB, input);
  26.  
  27.     clearListOnLoad();
  28.     onValue(productsInDB, loadProducts);
  29.  
  30.     clearInputField();
  31.   }
  32. }
  33.  
  34. function loadProducts(snapshot) {
  35.   if (snapshot.exists()) {
  36.     const data = snapshot.val();
  37.  
  38.     ulElement.append(...Object.entries(data).map(createListElement));
  39.   }
  40. }
  41.  
  42. function createListElement(data) {
  43.   const [id, product] = data;
  44.  
  45.   const li = document.createElement('li');
  46.   const btn = document.createElement('button');
  47.   const div = document.createElement('div');
  48.  
  49.   li.textContent = product;
  50.   li.id = id;
  51.   btn.textContent = 'Delete';
  52.   btn.addEventListener('click', onDelete);
  53.   div.appendChild(btn);
  54.   div.id = 'del-btn';
  55.  
  56.   li.appendChild(div);
  57.  
  58.   return li;
  59. }
  60.  
  61. function onDelete(e) {
  62.   const liElement = e.target.parentElement.parentElement;
  63.   const product = ref(database, `products/${liElement.id}`);
  64.  
  65.   remove(product);
  66.   clearListOnLoad();
  67.   onValue(productsInDB, loadProducts);
  68. }
  69.  
  70. function clearInputField() {
  71.   inputElement.value = '';
  72. }
  73.  
  74. function clearListOnLoad() {
  75.   ulElement.innerHTML = '';
  76. }
  77.  
  78. function isEmptyString(input) {
  79.   if (input == '') {
  80.     return true;
  81.   }
  82.  
  83.   return false;
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement