Ayan Das
Ayan Das

Reputation: 19

Using Riverpod, how to update a list locally, until the database from which list is being fetched has updated

I need to fetch a list of Messages using Riverpod provider, from Firestore. When I send a new message, I add the new message in Firestore, which updates the provider. But until the Firestore database has been updated, I want to add that message to the list of messages locally. How do I approach this? Please provide some example code.

p.s - I'm using riverpod code generation

Upvotes: 0

Views: 149

Answers (1)

Ayan Das
Ayan Das

Reputation: 19

It was pretty simple actually,

@riverpod
class MessagesById extends _$MessagesById {
  @override
  Stream<Iterable<Message>> build(String chat) {
    return _getMessages(1);
  }

  Stream<Iterable<Message>> _getMessages(int page) {
   //
  }
  
  // For adding item locally until the database updates
  add(MessagePayload payload, String id) {
    final msg = Message.fromPayload(payload);
    state = AsyncValue.data([msg, ...state.value!]);
  }

}

When adding a new item from the repository code, call ref.read(messageByIdProvider(id).notifier).add(item). This adds the item locally, and when Firebase gets updated it gets automatically overridden because messagebyIdProvider is subscribed to firebase.

Upvotes: 0

Related Questions