自分が送信したメッセージを削除したいです。クリックした要素をfirestoreのドキュメントから削除したいのですがうまくいきません。
以下のコードで試そうとしていること
それぞれの要素のドキュメントのidを配列に格納してクリックしたindex番目の要素を削除しようとしています。違うやり方でもよいのでどなたかご教授ください。
// クリックした要素の削除の部分がおそらく間違っています。
html
1<h1> 2 Free Chat 3 </h1> 4 5 <div class="login-btn"> 6 <button id="login">Login</button> 7 <button id="logout" class="hidden">Logout</button> 8 </div> 9 10 <ul id="messages" class="hidden"></ul> 11 <form autocomplete="off" class="hidden"> 12 <input type="text" id="message" placeholder="your message..."> 13 <button>送信</button> 14 </form>
js
1const db = firebase.firestore(); 2 const auth = firebase.auth(); 3 let me = null; 4 5 const collection = db.collection('messages'); 6 7 8 const message = document.getElementById('message'); 9 const form = document.querySelector('form'); 10 const login = document.getElementById('login'); 11 const logout = document.getElementById('logout'); 12 const messages = document.getElementById('messages'); 13 let dd; 14 15 16 17 login.addEventListener('click', () => { 18 auth.signInAnonymously(); 19 }) 20 21 logout.addEventListener('click', () => { 22 auth.signOut(); 23 }) 24 25 auth.onAuthStateChanged(user => { // ログイン状態の監視 26 if (user) { // ログイン時の処理 27 me = user; 28 // console.log(me); 29 30 while (messages.firstChild) { 31 messages.removeChild(messages.firstChild); 32 } 33 34 collection.orderBy('created').onSnapshot(snapshot => { 35 snapshot.docChanges().forEach(change => { 36 if (change.type === 'added') { 37 const li = document.createElement('li'); 38 const div = document.createElement('div'); 39 const d = change.doc.data(); 40 dd = change.doc.id; 41 42 div.classList.add('text'); 43 44 // 自分の投稿を右側に表示 45 if (me.uid === d.uid) { 46 li.classList.add('right-side'); 47 } else { 48 li.classList.add('left-side'); 49 } 50 div.textContent = d.uid.substr(0, 8) + ': ' + d.message; 51 52 li.appendChild(div); 53 54 collection.get().then(snapshot => { 55 56 // doc.idの配列を作る 57 const docSnapshot = snapshot.docs; 58 const items = docSnapshot.map(doc => doc.id); 59 console.log(items); 60 61 // クリックした要素の削除 62 div.addEventListener('click', () => { 63 if (li.classList.contains('right-side')) { 64 if (confirm('削除しますか?')) { 65 items.forEach(function(item, index) { 66 collection.doc(items[index]).delete().then(() => { 67 console.log("Document successfully deleted!") 68 }).catch((error) => { 69 console.log(error); 70 }) 71 72 }); 73 74 } 75 } 76 }); 77 }) 78 79 messages.appendChild(li); 80 } 81 }); 82
あなたの回答
tips
プレビュー