0
function renderlist(doc) {
  const listmon = document.querySelector("#item-list");

  db.collection("cafes")
    .get()
    .then((snapshot) => {
      list(snapshot.docs);
    });

  const list = (data) => {
    let html = "";
    data.forEach((doc) => {
      const guide = doc.data();
      auth.onAuthStateChanged((user) => {
        if (user) {
          const li = `<li class=${user.uid}>
        <div class="card">
        <a
          href="#"
          class="btn btn-fix text-left"
          data-toggle="modal"
          data-target="#exampleModal"
        >
          <div class="card-block">
            <h4 class="card-title text-dark">${guide.name}</h4>
            <p class="card-text text-dark">
              ${guide.city}
            </p>
            <a href="#" class="btn btn-primary" id="delete" onclick="arun (){ 
              console.log("clicked");
            
          };">delete</a>
            
            <p class="card-text">
              <small class="text-muted">Last updated 3 mins ago</small>
            </p>
          </div>
        </a>
      </div>
        </li>
        <div
      class="modal "
      id="exampleModal"
      tabindex="-1"
      aria-labelledby="exampleModalLabel"
      aria-hidden="true"
    >
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
            <button
              type="button"
              class="close"
              data-dismiss="modal"
              aria-label="Close"
            >
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div
            class="modal-body"
            data-toggle="modal"
            data-target="#exampleModal"
          >
          ${guide.name}
          </div>
          <div class="modal-footer">
            <button
              type="button"
              class="btn btn-secondary"
              data-dismiss="modal"
            >
              Close
            </button>
            <button type="button" class="btn btn-primary">Save changes</button>
          </div>
        </div>
      </div>
    </div>`;
          html += li;
          listmon.innerHTML = html;
        } else {
          console.log("logged out");
        }
      });
    });
  };
}

i created it using javascript and i want to remove it by clicking a button also i have used user uid as the lists id, when ever i click the button it should remove the list and from cloud firestore it would also be great if somebody could tell me how to only show users data to that particular user,sorry for the language and thanks in advance

1 Answers1

0

I created this simple example to list users with the methods add, delete and show info.

These Firestore/firebase documents [Queries | Modify a document | resource parts ] can be helpful for you to understand better the methods that I used, please feel free to modify this code.


<html>

<head>
    <script src="https://www.gstatic.com/firebasejs/7.18.0/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/7.18.0/firebase-firestore.js"></script>
</head>

<body>

    <h1>Users</h1>

    <div class="content">

        <form id="add-user-form">
            <input type="text" name="name" placeholder="user Name">
            <input type="text" name="location" placeholder="user Location">
            <button type="submit">Submit</button>
        </form>

        <ul id="user-list">
            <div id="loader">Loading...</div>
        </ul>

    </div>

    <script>
    // Your web app's Firebase configuration
        var firebaseConfig = {
            
        };
        // Initialize Firebase
        firebase.initializeApp(firebaseConfig);
        const db = firebase.firestore();
        
        const userList = document.querySelector("#user-list");
        const form = document.querySelector("#add-user-form");


        //add listener to form, to create new users and avoid default form action
        form.addEventListener("submit", e => {
          e.preventDefault();
          db.collection("users").add({
            name: form.name.value,
            location: form.location.value
          });
          form.name.value = "";
          form.location.value = "";
        });

        //Create the users list with the firestore data
        function renderuser(doc) {

          //creating html elements
          let li = document.createElement("li");
          let name = document.createElement("span");
          let del = document.createElement("button");
          let info = document.createElement("button")

          //add docuemnt ID to the list element
          li.setAttribute("data-id", doc.id);
          name.textContent = doc.data().name ;
          location.textContent = doc.data().location;

          //labels of the buttons
          // i= info and x= delete user
          info.textContent="i"
          del.textContent = "X";

          // add onclick action to the buttons
          del.onclick=function(){deleteUser(doc.id);}
          info.onclick=function(){getData(doc.id);} 

          // add elements to the list element
          li.appendChild(name);
          li.appendChild(del);
          li.appendChild(info);

          // add list element to the list
          userList.appendChild(li);

          
        }
          
        function deleteUser(id){
          db.collection("users")
              .doc(id)
              .delete();
        }

        // Getting Data
        function getData(id) {
          // __name__ is the reference for the id in firestore
          db.collection("users").where("__name__", "==", id).get()
            .then(function(querySnapshot) {
                querySnapshot.forEach(function(doc) {
                    // doc.data() is never undefined for query doc snapshots
                    console.log(doc)

                    //this alert simulate the modal 
                    alert("name: "+doc.data().name+"\nlocation: "+doc.data().location)
                });
            })
        }

        //this is not used but this is the method to update the data of a docuemnt(User)
        function updateData(id,name,location){
          db.collection("users").doc(id).set({
              name: name,
              location: location
          }).then(function() {
            alert("Document successfully written!");
          })
          .catch(function(error) {
              alert("Error writing document: ", error);
          });
        }


        // Realtime listener
        // this function keep updated the list 
        function getRealtimeData() {
          document.querySelector("#loader").style.display = "block";
          //query all users
          db.collection("users")
            .orderBy("name")
            .onSnapshot(snapshot => {
              document.querySelector("#loader").style.display = "none";
              let changes = snapshot.docChanges();
              changes.forEach(change => {
                if (change.type === "added") {
                  //add new users to the list on frist load this create the list of existent users
                  renderuser(change.doc);
                } else if (change.type === "removed") {
                  //if an user is deleted this will remove the element of the list
                  let li = userList.querySelector(`[data-id=${change.doc.id}]`);
                  userList.removeChild(li);
                }
              });
            });
          }

        //first run 
        getRealtimeData();

    </script>
</body>

</html>
Jan Hernandez
  • 4,414
  • 2
  • 12
  • 18