Wawan
Wawan

Reputation: 3

Ionic Angular Firestore: refresh list after deleting an element

I can't manage to refresh my list of elements after I delete an item. And, what I DO NOT understand: why does it work after adding an element. What's the difference? I looked for multiple solutions, but I didn't find a good one.

My service

addWord(word: Word) {
    db.collection('words').add({
      name: this.toolsService.upperFirstletter(word.name),
      description: word.description
    })
      .then(() => {
        this.toastService.toastSuccess(`Le mot ${word.name} a bien créé !`);
      })
      ...
    this.emitWords();
  }

deleteWord(word: Word) {
    db.collection('words').doc(word.id).delete()
      .then(() => {
        this.toastService.toastSuccess(`Le mot ${word.name} a bien été supprimé !`);
      })
      ...
    this.emitWords();
  }

emitWords() {
    const listWords: Word[] = [];
    const wordCollection = db.collection('words').orderBy('name', 'asc').get();
    wordCollection
      .then((querySnapShot) => {
        querySnapShot.forEach((doc) => {
          listWords.push(
            new Word(
              doc.id,
              doc.data().name,
              doc.data().description
            )
          );
          this.listWords$.next(listWords.slice());
        });
      })
    ...
  }

It works with add() but it doesn't with delete(). Thanks for the help!

Upvotes: 0

Views: 175

Answers (1)

Tarik Huber
Tarik Huber

Reputation: 7398

If you have enabled offline capabilities for firestore don't use then or await. Just run your code as if it's sinchronous:

addWord(word: Word) {
    db.collection('words').add({
      name: this.toolsService.upperFirstletter(word.name),
      description: word.description
    })
     
        this.toastService.toastSuccess(`Le mot ${word.name} a bien créé !`);
      
      
      ...
    
  }

deleteWord(word: Word) {
    db.collection('words').doc(word.id).delete()
      
        this.toastService.toastSuccess(`Le mot ${word.name} a bien été supprimé !`);
        
      
      ...
   
  }

Ant for a realtime listener use onSnaphost like here:

db.collection("words").orderBy('name', 'asc')
    .onSnapshot((querySnapshot) => {
        var words = [];
        querySnapshot.forEach((doc) => {
            words .push(doc.data().name);
        });
        console.log("Current cities in CA: ", words.join(", "));
    });

That way you don't need to call emitWords each time you change something.

Upvotes: 1

Related Questions