Run an async action after a valid submit, like React's server actions and useActionState: pending state, server errors and no double submits.
An action is an async function that receives the validated values, the way a server action does. It runs on GPUI's foreground executor, so it works the same on desktop and in the single-threaded web build. Try the name acme for a field error, or the EU West region for a form error.
use std::time::Duration;
use gpui::{div, prelude::*, px, App, SharedString, Window};
use crate::theme::ActiveTheme;
use crate::ui::alert::{Alert, AlertIcon, AlertVariant};
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::card::Card;
use crate::ui::form::{field, string, Form, FormExt, Schema, ServerErrors};
use crate::ui::select::{Select, SelectOption};
use crate::ui::spinner::Spinner;
use crate::ui::toast::{toast, Toast, Toaster};
#[derive(Clone, Debug, PartialEq)]
struct NewProject {
name: String,
region: String,
}
const REGIONS: [(&str, &str); 3] = [
("us-east", "US East (Virginia)"),
("eu-west", "EU West (Ireland)"),
("ap-northeast", "Asia Pacific (Seoul)"),
];
fn project_schema() -> Schema<NewProject> {
Schema::<NewProject>::new().field(
field!(name),
string()
.min(2, "Project name must be at least 2 characters.")
.max(24, "Project name must be at most 24 characters.")
.refine(
|name| name.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-'),
"Use lowercase letters, numbers and dashes.",
),
)
}
/// Stands in for a request to your backend: it answers after a second and a half.
async fn create_project(project: NewProject, cx: gpui::AsyncApp) -> Result<(), ServerErrors> {
cx.background_executor().timer(Duration::from_millis(1500)).await;
if project.name == "acme" {
return Err(ServerErrors::new().field("name", "That name is taken."));
}
if project.region == "eu-west" {
return Err(ServerErrors::new().form("EU West is at capacity right now. Pick another region."));
}
Ok(())
}
pub fn form_actions(window: &mut Window, cx: &mut App) -> impl IntoElement {
let form = window.use_keyed_state("form-actions", cx, |_, _| {
Form::new(NewProject {
name: String::new(),
region: "us-east".into(),
})
.schema(project_schema())
.action(create_project)
.on_success(|project, _, cx| {
toast(
Toast::new("Project created").description(format!("{} is live in {}.", project.name, project.region)),
cx,
)
})
});
let region_open = window.use_keyed_state("form-actions-region-open", cx, |_, _| false);
let name = form.input(field!(name), window, cx, |input| input.placeholder("acme-web"));
let f = form.read(cx);
let pending = f.is_pending();
let spinner_color = cx.theme().primary_foreground;
let region = REGIONS
.iter()
.fold(
Select::new(
"form-actions-region",
Some(SharedString::from(f.values().region.clone())),
*region_open.read(cx),
)
.width(px(398.)),
|select, (value, label)| select.option(SelectOption::new(*value, *label)),
)
.on_open_change(move |next, _, cx| {
region_open.update(cx, |open, cx| {
*open = *next;
cx.notify();
})
})
.on_change(form.on_change_with(field!(region), |region: &mut String, value: &SharedString| {
*region = value.to_string()
}));
div()
.w(px(448.))
.flex()
.flex_col()
.child(
Card::new()
.title("Create project")
.description("Deploy your new project in one click.")
.child(
div()
.flex()
.flex_col()
.gap_6()
.when_some(f.form_error(), |this, error| {
this.child(
Alert::new("Couldn't create the project")
.description(error)
.variant(AlertVariant::Destructive)
.icon(AlertIcon::CircleAlert),
)
})
.child(
f.field("name")
.label("Name")
.description("Lowercase letters, numbers and dashes.")
.child(name),
)
.child(f.field("region").label("Region").child(region)),
)
.footer(
div()
.flex()
.gap_2()
.child(
Button::new("form-actions-reset", "Reset")
.variant(ButtonVariant::Outline)
.on_click(form.handle_reset()),
)
.child(
Button::new("form-actions-submit", if pending { "Creating" } else { "Create project" })
.disabled(pending)
.when(pending, |button| button.leading(Spinner::new().color(spinner_color)))
.on_click(form.handle_submit()),
),
),
)
.child(Toaster::new())
}Writing an action
Give the form an async fn (or a closure returning a future) that takes the values and an AsyncApp. Return Ok(()) on success; on_success then runs with the values, which is the place for a toast or navigation.
/// Stands in for a request to your backend: it answers after a second and a half.
async fn create_project(project: NewProject, cx: gpui::AsyncApp) -> Result<(), ServerErrors> {
cx.background_executor().timer(Duration::from_millis(1500)).await;
if project.name == "acme" {
return Err(ServerErrors::new().field("name", "That name is taken."));
}
if project.region == "eu-west" {
return Err(ServerErrors::new().form("EU West is at capacity right now. Pick another region."));
}
Ok(())
}let form = window.use_keyed_state("form-actions", cx, |_, _| {
Form::new(NewProject {
name: String::new(),
region: "us-east".into(),
})
.schema(project_schema())
.action(create_project)
.on_success(|project, _, cx| {
toast(
Toast::new("Project created").description(format!("{} is live in {}.", project.name, project.region)),
cx,
)
})
});Pending state
While the action runs, is_pending() is true. Disable the submit button and show a Spinner in it:
Button::new("form-actions-submit", if pending { "Creating" } else { "Create project" })
.disabled(pending)
.when(pending, |button| button.leading(Spinner::new().color(spinner_color)))| SubmitState::Idle | Not submitted since the form was created or reset. |
| SubmitState::Pending | The action is running. Further submits are ignored. |
| SubmitState::Succeeded | Valid, and the action returned Ok. on_success has run. |
| SubmitState::Failed | Invalid, or the action returned ServerErrors. |
Server errors
Return ServerErrors to report what the server rejected. .field(name, message) shows an error on a field, focuses it, and clears once the user edits that field. .form(message) is about the submission as a whole; read it back with form_error(), for example in an Alert. The next submit clears it.
Err(ServerErrors::new().field("name", "That name is taken."))
Err(ServerErrors::new().form("EU West is at capacity right now. Pick another region."))Preventing double submit
submit returns early while an action is pending, so a second click, or Enter in a field, can't send the request twice, even if you forget to disable the button. reset drops the running action, which cancels it.