Skip to main content

Module remote

Module remote 

Source
Expand description

Queries and commands: data and mutations that aren’t tied to a route, inspired by SvelteKit’s remote functions.

A route’s load fetches what its page needs before it is shown. Some data doesn’t belong to a route, though: a badge in a layout, an autocomplete, a count that several pages show. And changing data is often async too (a POST to a backend), which a view can’t await.

  • A Query is async data that any view can read with Remote::query. The value is the query’s input, and also its cache key: views reading equal queries share one result.
  • A Command is an async mutation, started from a view with CommandHandle::run. Its state (pending, output, error) belongs to the view, and when it succeeds it refreshes the loads and queries that depend on what it changed.
use egui::Ui;
use egui_kit::RouteError;
use egui_kit::extract::Remote;
use egui_kit::remote::{Command, Query};

#[derive(Clone, Default)]
struct AppState;

/// How many todos there are.
#[derive(Clone, PartialEq)]
struct TodoCount;

impl Query<AppState> for TodoCount {
    type Output = usize;

    async fn run(self, _state: AppState) -> Result<usize, RouteError> {
        Ok(3) // e.g. a `GET /todos/count`
    }

    fn depends(&self) -> Vec<String> {
        vec!["todos".into()]
    }
}

struct AddTodo(String);

impl Command<AppState> for AddTodo {
    type Output = ();

    async fn run(self, _state: AppState) -> Result<(), RouteError> {
        Ok(()) // e.g. a `POST /todos`
    }

    fn refreshes(&self) -> Vec<String> {
        vec!["todos".into()]
    }
}

fn view(ui: &mut Ui, remote: Remote<'_, AppState>) {
    match remote.query(TodoCount).current() {
        Some(count) => ui.label(format!("{count} todos")),
        None => ui.spinner(),
    };

    let add = remote.command::<AddTodo>();
    if ui.add_enabled(!add.is_pending(), egui::Button::new("Add")).clicked() {
        add.run(AddTodo("Buy milk".into()));
    }
    if let Some(error) = add.error() {
        ui.label(error.message);
    }
}

Like loads, queries and commands are polled by the router, so no async runtime is needed, and their futures don’t have to be Send.

§Caching

A query runs the first time a view reads it, and its result is kept for as long as views keep reading it: it is dropped after a frame in which no view did. While it reruns (after an invalidation or a refresh), QueryState::current still has the previous value.

Structs§

CommandHandle
A view’s handle to the command C, from Remote::command.
QueryState
A query’s result, as seen by a view: see Remote::query.
Remote
Queries and commands, in views: see the module docs.

Traits§

Command
An async mutation that views start with CommandHandle::run.
Query
Async data that views read with Remote::query, cached by value.