Mutations
Mutations handle write operations: creating a user, updating a record, deleting a resource. Unlike Queries, mutations don’t run automatically. You trigger them explicitly, and they manage their own loading/success/failure lifecycle.
A mutation does not touch the query cache on its own. If you need to invalidate or refetch queries after a mutation succeeds, do that in an on_success callback. The library doesn’t guess which queries a mutation should affect.
use_mutation
Section titled “use_mutation”pub fn use_mutation<V, T, E, C>( options: impl Into<MutationOptions>, cx: &mut Context<C>,) -> (Entity<MutationResource<V, T, E>>, Subscription)Creates a new MutationResource entity and returns it together with the Subscription that keeps its observer alive; store both on your view struct. The entity starts in the Idle state: pass () for the default retry behavior (no retries) or a MutationOptions to change it. use_mutation reads only retry_policy from the options; mutation garbage collection is governed by the QueryClient global’s GC time (default 5 minutes, set with QueryClient::with_gc_time). Read from the entity during render to show loading spinners, error messages, or success state.
use gpui::{Entity, Subscription};use gpui_query::{use_mutation, MutationResource};
struct UserForm { create_user: Entity<MutationResource<NewUser, User>>, _mutation_sub: Subscription,}
impl UserForm { fn new(cx: &mut Context<Self>) -> Self { let (create_user, _mutation_sub) = use_mutation((), cx); Self { create_user, _mutation_sub } }}The returned entity is a GPUI Entity, so you observe it like any other entity: call entity.read(cx) to inspect status, data, and error fields during render.
mutate
Section titled “mutate”pub fn mutate<V, T, E, C, F, Fut>( entity: &Entity<MutationResource<V, T, E>>, variables: V, mutator: F, cx: &mut Context<C>,)Triggers a mutation on the entity. It transitions the resource to Loading, spawns an async task running your mutator closure, and handles the outcome (including retries if the entity has a retry policy).
The mutator closure receives the variables and must return a Future<Output = Result<T, E>>. A call while the entity is already loading is ignored. Otherwise it stores the new variables, clears the error, and resets the retry count; previous success data stays readable until the new attempt settles (replaced on success, cleared on failure or cancel).
use gpui_query::{use_mutation, mutate};
mutate(&self.create_user, NewUser { name: "Alice" }, |vars| async move { let resp = reqwest::post("/api/users") .json(&vars) .send() .await?; let user: User = resp.json().await?; Ok::<User, MyError>(user)}, cx);mutate holds a WeakEntity reference internally, so dropping the entity before the async task finishes is safe. The task exits.
Concurrency
Section titled “Concurrency”A call made while the entity is still Loading is a no-op: the built-in is_loading() guard ignores it and the in-flight mutation keeps running. You don’t need a manual entity.read(cx).is_loading() check to prevent concurrent mutations. mutate_with_callbacks, mutate_by_ref, and mutate_arc behave the same way.
mutate_with_callbacks
Section titled “mutate_with_callbacks”pub fn mutate_with_callbacks<V, T, E, C, F, Fut>( entity: &Entity<MutationResource<V, T, E>>, variables: V, mutator: F, callbacks: MutationCallbacks<T, E>, cx: &mut Context<C>,)Identical to mutate but accepts a MutationCallbacks struct that fires on the final outcome. Callbacks run on the terminal outcome: first success, exhausted retries, or a mutation ended early by cancel(), reset(), or the entity being dropped. They do not fire on intermediate retry attempts.
This is where you invalidate query caches after a successful write:
use gpui_query::{mutate_with_callbacks, MutationCallbacks};
mutate_with_callbacks( &self.create_user, NewUser { name: "Alice" }, |vars| async move { Ok::<User, MyError>(create_user(vars).await) }, MutationCallbacks::new() .on_success(|data| { // invalidate user list queries so they refetch println!("created user: {:?}", data); }) .on_error(|err| { eprintln!("mutation failed: {:?}", err); }), cx,);See the MutationCallbacks section for the full callback API.
mutate_by_ref
Section titled “mutate_by_ref”pub fn mutate_by_ref<V, T, E, C, F, Fut>( entity: &Entity<MutationResource<V, T, E>>, variables: V, mutator: F, cx: &mut Context<C>,)Same trigger as mutate, but the mutator receives &V borrowed from the stored Arc<V>, so there is no V::clone per attempt. V: Clone is still required, because begin stores an owned copy.
use gpui_query::mutate_by_ref;
mutate_by_ref(&self.create_user, NewUser { name: "Alice" }, |vars| { let name = vars.name.clone(); async move { Ok::<User, MyError>(create_user(name).await) }}, cx);The returned future must be 'static, so clone what you need out of vars before the async move block.
mutate_arc
Section titled “mutate_arc”pub fn mutate_arc<V, T, E, C, F, Fut>( entity: &Entity<MutationResource<V, T, E>>, variables: Arc<V>, mutator: F, cx: &mut Context<C>,)mutate_by_ref taking Arc<V> directly, so callers can share one variables buffer across calls. Both variants take the same Fn(&V) mutator, and neither accepts MutationCallbacks.
use_mutation_state
Section titled “use_mutation_state”pub fn use_mutation_state<V, T, E, C>(cx: &mut Context<C>) -> Vec<Entity<MutationResource<V, T, E>>>Returns a snapshot of all MutationResource entities matching the (V, T, E) type triple registered in the global QueryClient. Useful for devtools or status bars that need to observe all mutations of a particular kind across the entire app.
Returns an empty Vec if no mutations exist for that type triple or if no QueryClient is set up.
use gpui_query::use_mutation_state;
let active_mutations = use_mutation_state::<NewUser, User, MyError, _>(cx);for entity in &active_mutations { let m = entity.read(cx); if m.is_loading() { // show a global spinner }}MutationResource<V, T, E>
Section titled “MutationResource<V, T, E>”The core state container for a single mutation. Three type parameters:
Vis the variables (input) type. What you pass into the mutation.Tis the success output type. The data returned on completion.Eis the error type. Defaults toQueryError.
Lifecycle
Section titled “Lifecycle”Every mutation goes through these states in order:
- Idle: initial state. No mutation has been triggered.
- Loading:
begin(variables)was called. The variables are stored, the error is cleared, and a fresh cancellation signal is created. - Success or Failure: the async task completes.
complete_success(data)stores the result and clears the error.complete_failure(error)stores the error and increments the retry counter.
If the entity has a retry policy and retries remain after a failure, the internal loop keeps the mutation in Loading via increment_retry() and prepare_retry() (observers never see a transient Failure between attempts) and runs the mutator again. complete_failure() runs only when retries are exhausted. retry() is a public manual Failure to Loading helper, not what the loop uses.
The loop calls reset_retry_count() right after the terminal complete_success and complete_failure, undoing complete_failure’s increment. A mutation driven through mutate or any of its variants always reads retry_count() == 0 once settled; the counter is non-zero only mid-flight between retry attempts, or when you drive the resource by hand.
Accessors
Section titled “Accessors”| Method | Return type | Description |
|---|---|---|
status() |
MutationStatus |
Current status enum |
data() |
Option<&T> |
Most recent success data |
error() |
Option<&E> |
Most recent error |
variables() |
Option<&V> |
Current or most recent variables |
retry_count() |
u32 |
How many retries have been attempted; the internal loop resets it to 0 once the mutation settles, so it reads non-zero only mid-flight or when you drive the resource by hand |
cancelled_count() |
u64 |
How many times this mutation has been cancelled |
retry_policy() |
&RetryPolicy |
The retry policy for this resource |
set_retry_policy(policy) |
() |
Replaces the retry policy for this resource |
signal() |
Option<&QuerySignal> |
The cancellation signal, if the mutation is in flight |
key() |
Option<&QueryKey> |
Optional query key for cache correlation |
Boolean helpers
Section titled “Boolean helpers”is_idle(), is_loading(), is_success(), is_failure() each return bool. These are convenience wrappers around status() checks.
Methods
Section titled “Methods”begin(variables) transitions to Loading. Stores the variables, clears any previous error and the GC timestamp, resets the retry count, and creates a fresh QuerySignal.
complete_success(data) transitions to Success. Stores the result data and clears the signal.
complete_failure(error) transitions to Failure. Stores the error, increments retry_count, and clears the signal.
should_retry() -> bool checks whether retry_count < max_retries according to the retry policy.
retry() -> bool attempts to transition from Failure back to Loading. Only succeeds when should_retry() is true and the current status is Failure. Preserves the original variables and creates a fresh signal. Returns true if the retry was initiated.
cancel(error) only acts while the status is Loading: it sets Failure with the given error, clears stored data, increments cancelled_count, and cancels the signal so in-flight async work can observe it. In any other status it returns without changing state.
reset() returns the resource to Idle and clears everything: data, error, variables, retry count, cancelled count, signal, and timestamp.
with_key(key) associates a QueryKey with this mutation for cache correlation. Returns self for builder-style chaining.
MutationStatus
Section titled “MutationStatus”pub enum MutationStatus { Idle, Loading, Success, Failure,}Each variant has a label() method returning a &'static str ("Idle", "Loading", "Success", "Failure").
MutationOptions
Section titled “MutationOptions”Options use_mutation accepts through Into: pass () for the defaults in the table, or build a custom set and hand it to use_mutation(opts, cx).
| Field | Type | Default | Description |
|---|---|---|---|
retry_policy |
RetryPolicy |
RetryPolicy::no_retries() |
Controls automatic retry on failure |
gc_time_ms |
u64 |
300_000 (5 minutes) |
Reserved: stored but not consumed today. Mutation GC runs off QueryClient::with_gc_time; Idle/Failure mutations survive that gc time, Success mutations twice it |
Builder methods:
use gpui_query::{MutationOptions, RetryPolicy};
let opts = MutationOptions::default() .retry_policy(RetryPolicy::new(3).with_exponential_backoff()) .gc_time(10 * 60 * 1_000); // 10 minutesMutationCallbacks<T, E>
Section titled “MutationCallbacks<T, E>”A struct of optional closures that fire when a mutation settles. Construct it with the builder pattern:
use gpui_query::MutationCallbacks;
let callbacks = MutationCallbacks::new() .on_success(|data: &User| { // called on successful completion }) .on_error(|err: &MyError| { // called after all retries exhausted }) .on_settled(|data: Option<&User>, err: Option<&MyError>| { // always called, regardless of outcome });Each field is an Option<Arc<...>>: on_success is Option<Arc<dyn Fn(&T) + Send + Sync>>, on_error is Option<Arc<dyn Fn(&E) + Send + Sync>>, and on_settled is Option<Arc<dyn Fn(Option<&T>, Option<&E>) + Send + Sync>>. The builder methods accept any closure that is Fn(..) + Send + Sync + 'static and wrap it in an Arc.
on_successreceives&T. Fires once on first success.on_errorreceives&E. Fires once when the mutation ends in failure, whether retries were exhausted or the mutation was cancelled, reset, or dropped early.on_settledreceivesOption<&T>andOption<&E>. Exactly one isSomeon a normal success or failure; both can beNonewhen the entity was dropped or reset mid-mutation. Fires after eitheron_successoron_error.
Callbacks fire on the final outcome only. Intermediate retry attempts do not trigger callbacks.
RetryPolicy
Section titled “RetryPolicy”Shared between queries and mutations. See the Queries page for the full reference. The defaults for mutations differ: use_mutation creates a resource with RetryPolicy::no_retries(), while MutationOptions::default() also defaults to no retries.
To add retries:
use gpui_query::RetryPolicy;
// Fixed 1-second delay, up to 3 retrieslet policy = RetryPolicy::new(3);
// Exponential backoff: 1s, 2s, 4s, capped at 30slet policy = RetryPolicy::new(3) .with_delay(1000) .with_exponential_backoff() .with_max_delay(30_000);Putting it together
Section titled “Putting it together”A complete example of a view that creates a user and invalidates the user list on success:
use gpui::{Context, Entity, Subscription, View};use gpui_query::{ use_mutation, mutate_with_callbacks, MutationCallbacks, MutationResource,};
struct UserForm { create_user: Entity<MutationResource<NewUser, User>>, _mutation_sub: Subscription,}
impl UserForm { fn new(cx: &mut Context<Self>) -> Self { let (create_user, _mutation_sub) = use_mutation((), cx); Self { create_user, _mutation_sub } }
fn handle_submit(&mut self, name: String, cx: &mut Context<Self>) { mutate_with_callbacks( &self.create_user, NewUser { name }, |vars| async move { Ok::<User, MyError>(api::create_user(&vars).await) }, MutationCallbacks::new() .on_success(|_user| { // Trigger a refetch of the user list query. // This is where you'd call invalidate_queries or // refetch on the relevant query entity. }) .on_error(|err| { eprintln!("create user failed: {:?}", err); }), cx, ); }}The mutation entity lives on the view struct. During render, read self.create_user.read(cx).status() to decide what to show. When the user submits the form, handle_submit fires the mutation. On success, the callback invalidates whatever queries need refreshing. The query cache is otherwise untouched.