riverpod icon indicating copy to clipboard operation
riverpod copied to clipboard

Support query mutation

Open rrousselGit opened this issue 1 year ago • 29 comments

A common use case is to trigger side-effects and have the UI listen to the status of that side-effect (such as showing a spinner/snackbar on error)

I don't think there is a neat way to support this without code-generation that wouldn't have fundamental flaws (like the inability to pass parameters).
But with the new code-generation syntax for providers, Riverpod should be able to support this

In particular, we could have:

@riverpod
class Example extends _$Example {
  @override
  Future<List<Todo>> build() => fetchTodoList();

  @mutation
  Future<void> addTodo(Todo todo) async {
    await http.post(...., todo.toJson());
  }
}

which would then be used inside widgets by doing:

Consumer(
  builder: (context, ref, child) {
    // as usual, nothing special
    List<Todo> todos = ref.watch(exampleProvider);

    // our UI listens to "addTodo" side-effects.
    // The returned AddTodoMutation object contains things like loading/error/result
    // of the mutation, similar to that of AsyncValue.
    AddTodoMutation addTodo = ref.watch(exampleProvider.addTodo);

    return SomeButton(
      // invoke the Example.addTodo method
      onTap: () => addTodo(Todo())
    );
  },
)

Mutations would also receive a custom ProviderObserver event for start/completion/failure, with an Invocation corresponding to the method invocation.

And of course, riverpod_graph & the devtool should be updated to show mutations

rrousselGit avatar Sep 21 '22 18:09 rrousselGit

Tagged as "2.1" but likely will come after. Consider this as a "planned"

rrousselGit avatar Sep 21 '22 18:09 rrousselGit

As a side note, the linter is too aggressive about read vs watch in provider definitions when you are using FutureProvider for mutations. (you don't always want to rerun a mutation when things change, in some cases it might make sense, but not always).

TimWhiting avatar Oct 08 '22 04:10 TimWhiting

You're not supposed to use FutureProvider for mutations to begin with.

rrousselGit avatar Oct 08 '22 06:10 rrousselGit