Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mutation: Optimistic updates #3938

Open
snapsl opened this issue Jan 18, 2025 · 6 comments
Open

Mutation: Optimistic updates #3938

snapsl opened this issue Jan 18, 2025 · 6 comments
Assignees
Labels
enhancement New feature or request

Comments

@snapsl
Copy link

snapsl commented Jan 18, 2025

How to implement optimistic updates with Riverpod mutations?

@rrousselGit
Copy link
Owner

final prevState = state;
try {
  state = <your optimistic update>

  return await repo.post();
} catch (err) {
  state = prevState;
}

@snapsl
Copy link
Author

snapsl commented Jan 18, 2025

Ops. I should have thought of that myself. 😅
This could be added to the docs.

Perhaps this could be automated so that Riverpod restores the previous state in the event of a mutation.error?

@rrousselGit
Copy link
Owner

We certainly could have a @Mutation(optimistic: true) or something

@rrousselGit
Copy link
Owner

The main challenge is that we can only automate it for immutable state.

And there's also the addec challenge of "what if the state changed in the meantime". Reverting it could revert more than needed.
But it could possibly be combined with #3887

@snapsl
Copy link
Author

snapsl commented Jan 18, 2025

I do believe that this should be the default setting, because if an update is not optimistic, this would result in a noop.
Yeah, scheduling of async mutation could get a problem.

@rrousselGit
Copy link
Owner

I don't think that should be the default.

But about race conditions, we could throw if the state is mutated outside of the mutation while the optimistic mutation is pending.
I'll think about it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants