You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Assume I have the providers below. I had the like/unlike code in an extension, which was working well. But I am trying to add optimistic updates, which kinda broke my extension-based approach, since I was unable to modify the state in my extension methods. Below code works fine (updates UI immediately, and then refreshes state from the server), but is obviously undesirable.
Obviously, the list updating could be extracted for each class, but that's not my issue... :) Is there some better way to do this? Sorry, might be obvious, but I really am not good enough to find a proper solution for this...
@riverpod
class Provider1 extends _$Provider1 {
@override
build...
Future<void> like(int id) async {
if (state.value != null) {
final updatedList = state.value!.map((post) {
if (post.id == id) {
return post.copyWith(isLiking: true);
}
return post;
}).toList();
state = AsyncData(updatedList);
}
await MyApi.likePost(id);
ref.invalidateSelf();
}
Future<void> unlike(int id) async {
if (state.value != null) {
final updatedList = state.value!.map((post) {
if (post.id == id) {
return post.copyWith(isLiking: false);
}
return post;
}).toList();
state = AsyncData(updatedList);
}
await MyApi.unlikePost(id);
ref.invalidateSelf();
}
}
@riverpod
class Provider2 extends _$Provider2 {
@override
build...
Future<void> like(int id) async {
if (state.value != null) {
final updatedList = state.value!.map((post) {
if (post.id == id) {
return post.copyWith(isLiking: true);
}
return post;
}).toList();
state = AsyncData(updatedList);
}
await MyApi.likePost(id);
ref.invalidateSelf();
}
Future<void> unlike(int id) async {
if (state.value != null) {
final updatedList = state.value!.map((post) {
if (post.id == id) {
return post.copyWith(isLiking: false);
}
return post;
}).toList();
state = AsyncData(updatedList);
}
await MyApi.unlikePost(id);
ref.invalidateSelf();
}
}
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
Assume I have the providers below. I had the like/unlike code in an extension, which was working well. But I am trying to add optimistic updates, which kinda broke my extension-based approach, since I was unable to modify the state in my extension methods. Below code works fine (updates UI immediately, and then refreshes state from the server), but is obviously undesirable.
Obviously, the list updating could be extracted for each class, but that's not my issue... :) Is there some better way to do this? Sorry, might be obvious, but I really am not good enough to find a proper solution for this...
Beta Was this translation helpful? Give feedback.
All reactions