Firebase returning same result after deletion

29 Views Asked by At

I have a function that deletes a document from my challenges collection in Firebase. After the deletion, it refreshes the challenges array in the state using the flutter_bloc library. But the issue is right after I delete a document, Firebase does not return the updated QuerySnapshot without the deleted document. The deleted document is still in the array. How I handle the state looks okay because I'm adding and updating without any issue in the same way.

Here is how I manage the state when deleting the document:

 on<DeleteChallengeEvent>((event, emit) async {
  emit(ChallengeDeleting());

  try {
    await _challengeRepository.deleteChallenge(event.challengeId);
    emit(ChallengeDeleted());

    // * refreshing challenges after deletion
    add(FetchChallengesEvent());
  } catch (e) {
    ChallengeDeletingError("Challenge deleting failed");
  }
});

Here is how I manage the state when Fetching the data from Firebase:

on<FetchChallengesEvent>((event, emit) async {
  emit(ChallengesLoading());

  try {
    final challenges = await _challengeRepository.getChallenges();

    emit(ChallengesLoaded(challenges));
  } catch (e) {
    emit(ChallengesError());
  }
});

Here are the states that I have:

sealed class ChallengesState extends Equatable {
 @override
 List<Object?> get props => [];
}

final class ChallengesInitial extends ChallengesState {}

class ChallengesLoading extends ChallengesState {}

class ChallengesLoaded extends ChallengesState {
 final List<Challenge> challenges;

 ChallengesLoaded(this.challenges);

 @override
 List<Object?> get props => [challenges];
}

class ChallengesError extends ChallengesState {}

class ChallengeDeleting extends ChallengesState {}

class ChallengeDeleted extends ChallengesState {}

class ChallengeDeletingError extends ChallengesState {
 final String errorMessage;

ChallengeDeletingError(this.errorMessage);
}

Here is the function where I deletes the document:

Future<void> deleteChallenge(String challengeId) async {
try {
  DocumentReference challengeRef =
      _firestore.collection("challenges").doc(challengeId);

  DocumentSnapshot challengeSnapshot = await challengeRef.get();
  String imageURL = await challengeSnapshot.get("imageURL");

  await challengeRef.delete();

  // * deleting the image associated with the challenge
  Reference imageRef = FirebaseStorage.instance.refFromURL(imageURL);
  await imageRef.delete();
} catch (e) {
  throw Exception('Failed to delete the challenge: $e');
}
}

Here is the function where I refresh or get the updated challenges:

 Future<List<Challenge>> getChallenges() async {
try {
  QuerySnapshot<Map<String, dynamic>> querySnapshot = await _firestore
      .collection('challenges')
      .orderBy("createdAt", descending: true)
      .get(const GetOptions(source: Source.server));
  List<Challenge> challenges = [];
  for (var doc in querySnapshot.docs) {
    Map<String, dynamic> data = doc.data();

    Challenge challenge = Challenge(
        id: doc.id,
        title: data['title'],
        description: data['description'],
        location: data['location'],
        country: data['country'],
        rules: data['rules'],
        startDateTime: data['startDateTime'].toDate(),
        endDateTime: data['endDateTime'].toDate(),
        completedPercentage: data['completedPercentage'],
        maximumParticipants: data['maximumParticipants'],
        registeredParticipants: data['registeredParticipants'],
        difficulty: data['difficulty'],
        imageURL: data['imageURL'],
        type: data['type'],
        rating: double.parse(data['rating']
            .toString()), // * converting firebase number format to double format
        categoryId: data["categoryId"]);

    challenges.add(challenge);
  }
  print("Challenges array length");
  print(challenges.length);

  return challenges;
} catch (e) {
  throw Exception('Failed to fetch challenges: $e');
}
}

I greatly appreciate it if you could help me to find out what's the issue.

0

There are 0 best solutions below