Optimistic Updates
Optimistic UI updates immediately render the expected result of a mutation before the server responds, giving users the perception of an instantaneous application.
If the mutation succeeds, the server's definitive response updates the cache. If the mutation fails, the application smoothly rolls back to the previous snapshot.
The Optimistic Update Pattern
In fquery_core, optimistic updates are handled in four steps using MutationObserver:
onMutate:- Capture a snapshot of current query data.
- Optimistically mutate the cache using
setQueryData. - Return the snapshot as the context.
mutationFn:- Send the asynchronous request to the server.
onError:- If an error occurs, use the snapshot returned in context to revert the cache.
onSettled:- Invalidate the query to ensure the client stays in exact sync with the server.
Complete Example
dart
final addTodoMutation = MutationObserver<Todo, Exception, String, List<Todo>>(
options: MutationOptions(
mutationFn: (text) => api.addTodo(text),
onMutate: (newTodoText) async {
// 1. Snapshot previous state
final previousTodos = cache.getQueryData<List<Todo>, Exception>(['todos']) ?? [];
// 2. Optimistically update cache with temporary item
final optimisticTodo = Todo(id: -1, text: newTodoText, isPending: true);
cache.setQueryData<List<Todo>, Exception>(['todos'], (current) {
return [...(current ?? []), optimisticTodo];
});
// 3. Return snapshot context for potential rollback
return previousTodos;
},
onError: (error, variables, rollbackSnapshot) {
// Rollback to previous state on failure
if (rollbackSnapshot != null) {
cache.setQueryData<List<Todo>, Exception>(['todos'], (_) => rollbackSnapshot);
}
print('Failed to add todo: $error');
},
onSettled: (data, error, variables, context) {
// Refetch in background to guarantee accuracy
cache.invalidateQueries(['todos']);
},
),
);