Get started
Introduction
Installation
Your first app
Tutorials
Fission tutorials
Manage iOS app state with reducers and local state
Core concepts
Components
State and effects
Protected routes
Server-side rendering
Styling
Testing
Deployment
Reference
API reference
Cookbook
Fission 0.16.0
Documentation version
Read the changelog →

Manage iOS app state with reducers and local state

Create library loans, record each return once and filter the desk without changing the underlying records.
iOS

What you will build

Keep loan records authoritative whilst draft entry, filtering and disclosure remain local presentation choices.
Enter actual book and borrower data instead of seeding preview-only loans
Apply an idempotent return transition and derive totals from records
Keep stable row identities without promising that unmounted local state survives
Returning a book changes a library record. Hiding returned books changes only what one desk displays. Both operations can make a row disappear, but they do not mean the same thing. If we put them in the same state bucket, a harmless display choice can become an accidental change to the library's data.
We will build a returns desk that starts empty and lets you enter loans yourself. A loan's return status belongs to application state because the list, totals and confirmation all describe that same fact. The unfinished entry form and the desk's filter belong to this component's retained UI state.

Create the app

Complete iOS setup if needed, then generate the shared project.
cargo install cargo-fission
fission init riverside-library
cd riverside-library
fission add-target ios --project-dir .
cargo add serde_yaml
Keep the generated src/main.rs. The files below provide normal native and Web launchers from the outset; the browser does not inject records which the iOS app never receives.

Run the finished example

fission run --target ios --project-dir .

1. Give each fact one owner

LibraryState.loans is the authority for the session's records. The summary derives counts from it instead of keeping a second pair of mutable counters. This matters because a return cannot update the row and leave a separately stored total behind.
The reducer block calls mark_returned, an ordinary synchronous Rust function. It selects by record ID, ignores an unknown ID and leaves an already returned loan unchanged. The function can therefore be tested without constructing a widget or inventing a second action format.
{"id":"fission-tabs-1","tabs":[{"index":0,"label":"src/app.rs","value":"src-app-rs"},{"index":1,"label":"src/app/state.rs","value":"src-app-state-rs"},{"index":2,"label":"src/app/loan_card.rs","value":"src-app-loan-card-rs"},{"index":3,"label":"src/app/summary.rs","value":"src-app-summary-rs"},{"index":4,"label":"src/app/screen.rs","value":"src-app-screen-rs"},{"index":5,"label":"src/i18n.rs","value":"src-i18n-rs"},{"index":6,"label":"src/lib.rs","value":"src-lib-rs"},{"index":7,"label":"preview/lib.rs","value":"preview-lib-rs"},{"index":8,"label":"i18n/en-US.yaml","value":"i18n-en-us-yaml"},{"index":9,"label":"i18n/es-ES.yaml","value":"i18n-es-es-yaml"}]}
{"id":"fission-tabs-1","index":0,"label":"src/app.rs","value":"src-app-rs"}
mod loan_card;
mod screen;
pub mod state;
mod summary;
pub use screen::LibraryLoanDesk;
pub use state::LibraryState;
{"id":"fission-tabs-1","index":1,"label":"src/app/state.rs","value":"src-app-state-rs"}
use fission::prelude::*;

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Loan {
    pub id: u64,
    pub title: String,
    pub borrower: String,
    pub returned: bool,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LibraryState {
    pub loans: Vec<Loan>,
    pub next_id: u64,
    pub last_returned_title: Option<String>,
    pub locale: Locale,
}

impl Default for LibraryState {
    fn default() -> Self {
        Self {
            loans: Vec::new(),
            next_id: 1,
            last_returned_title: None,
            locale: Locale::from("en-US"),
        }
    }
}

impl GlobalState for LibraryState {}

pub fn add_loan(state: &mut LibraryState, title: &str, borrower: &str) -> bool {
    let (title, borrower) = (title.trim(), borrower.trim());
    if title.is_empty() || borrower.is_empty() {
        return false;
    }
    let Some(next_id) = state.next_id.checked_add(1) else {
        return false;
    };
    state.loans.push(Loan {
        id: state.next_id,
        title: title.to_owned(),
        borrower: borrower.to_owned(),
        returned: false,
    });
    state.next_id = next_id;
    true
}

pub fn mark_returned(state: &mut LibraryState, loan_id: u64) {
    let Some(loan) = state.loans.iter_mut().find(|loan| loan.id == loan_id) else {
        return;
    };
    if loan.returned {
        return;
    }
    loan.returned = true;
    state.last_returned_title = Some(loan.title.clone());
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn returning_updates_one_record_and_is_idempotent() {
        let mut state = LibraryState::default();
        assert!(add_loan(&mut state, "Book A", "Reader A"));
        assert!(add_loan(&mut state, "Book B", "Reader B"));
        mark_returned(&mut state, 2);
        assert!(!state.loans[0].returned);
        assert!(state.loans[1].returned);
        let expected = state.clone();
        mark_returned(&mut state, 2);
        mark_returned(&mut state, 999);
        assert_eq!(state, expected);
    }

    #[test]
    fn invalid_input_does_not_allocate_an_id() {
        let mut state = LibraryState::default();
        assert!(!add_loan(&mut state, " ", "Reader"));
        assert_eq!(state.next_id, 1);
        assert!(state.loans.is_empty());
    }
}
{"id":"fission-tabs-1","index":2,"label":"src/app/loan_card.rs","value":"src-app-loan-card-rs"}
use super::state::{mark_returned, LibraryState};
use fission::prelude::*;

fission_component! {
    pub LoanCard<LibraryState> {
        props { loan_id: u64 }
    }
    view(card, state, cx) {
        let tokens = &cx.view.env().theme.tokens;
        let loan = state.loans.iter().find(|loan| loan.id == card.loan_id);
    } => if let Some(loan) = loan {
      SemanticsRegion(
        identifier: Some(format!("library.loan.{}", card.loan_id)),
        child: Container(
        Column(gap: tokens.spacing.s, children: [
            Text(loan.title.clone()).weight(tokens.typography.font_weight_semibold),
            Text(cx.tr("library.borrower").replace("{name}", &loan.borrower)),
            Text(if loan.returned { cx.tr("library.returned") } else { cx.tr("library.on_loan") }),
            Button(
                child: Text(cx.tr("library.return")), key: "return-loan",
                disabled: loan.returned,
                on_press: reduce { mark_returned(state, card.loan_id); },
            ),
        ]),
    )
    .padding_all(tokens.spacing.m)
    .border(tokens.colors.border, 1.0)
    .border_radius(tokens.radii.medium),
      )
    } else {
        Spacer()
    }
}
{"id":"fission-tabs-1","index":3,"label":"src/app/summary.rs","value":"src-app-summary-rs"}
use super::state::LibraryState;
use fission::prelude::*;

fission_component! {
    pub LoanSummary<LibraryState> {}
    view(_summary, state, cx) {
        let returned = state.loans.iter().filter(|loan| loan.returned).count();
        let active = state.loans.len() - returned;
        let tokens = &cx.view.env().theme.tokens;
    } => Column(gap: tokens.spacing.s, children: [
        Text(cx.tr("library.active_total").replace("{count}", &active.to_string())),
        Text(cx.tr("library.returned_total").replace("{count}", &returned.to_string())),
    ])
}
{"id":"fission-tabs-1","index":4,"label":"src/app/screen.rs","value":"src-app-screen-rs"}
use super::{
    loan_card::LoanCard,
    state::{add_loan, LibraryState},
    summary::LoanSummary,
};
use fission::prelude::*;

fission_component! {
    pub LibraryLoanDesk<LibraryState> {
        state {
            title: String = String::new(),
            borrower: String = String::new(),
            show_returned: bool = false,
        }
    }
    view(desk, library, cx) {
        let tokens = &cx.view.env().theme.tokens;
        let visible: Vec<_> = library.loans.iter()
            .filter(|loan| desk.show_returned || !loan.returned).collect();
    } => SafeArea(
        child: Scroll(
            child: Container(Column(gap: tokens.spacing.m, children: [
                Text(cx.tr("library.heading")).size(tokens.typography.heading2_size),
                Text(cx.tr("library.session")),
                Row(gap: tokens.spacing.s, children: [
                    Button(
                        child: Text(cx.tr("language.english")), key: "english",
                        on_press: reduce { library.locale = Locale::from("en-US"); },
                    ),
                    Button(
                        child: Text(cx.tr("language.spanish")), key: "spanish",
                        on_press: reduce { library.locale = Locale::from("es-ES"); },
                    ),
                ]),
                FormControl(
                    label: Some(cx.tr("library.title")),
                    required: true,
                    child: TextInput(
                        value: desk.title.clone(),
                        bind(on_input): to(desk.title),
                    ),
                ),
                FormControl(
                    label: Some(cx.tr("library.reader")),
                    required: true,
                    child: TextInput(
                        value: desk.borrower.clone(),
                        bind(on_input): to(desk.borrower),
                    ),
                ),
                Button(
                    child: Text(cx.tr("library.add")), key: "add-loan",
                    disabled: desk.title.trim().is_empty() || desk.borrower.trim().is_empty()
                        || library.next_id == u64::MAX,
                    on_press: reduce {
                        if add_loan(library, &desk.title, &desk.borrower) {
                            desk.title.clear();
                            desk.borrower.clear();
                        }
                    },
                ),
                LoanSummary,
                Button(
                    child: Text(if desk.show_returned { cx.tr("library.hide_returns") } else { cx.tr("library.show_returns") }),
                    key: "toggle-returns",
                    on_press: reduce { desk.show_returned = !desk.show_returned; },
                ),
                if visible.is_empty() { Text(cx.tr("library.empty")) },
                for loan in visible {
                    LoanCard(loan.id, key: loan.id)
                },
                if let Some(title) = &library.last_returned_title {
                    Text(cx.tr("library.confirmation").replace("{title}", title))
                },
            ]))
            .padding_all(tokens.spacing.l),
        ),
    )
}
{"id":"fission-tabs-1","index":5,"label":"src/i18n.rs","value":"src-i18n-rs"}
use fission::i18n::{Locale, TranslationBundle};
use fission::prelude::*;
use std::collections::HashMap;

pub fn create_env() -> Env {
    let mut env = Env::default();
    env.locale = Locale::from("en-US");
    for (locale, source) in [
        ("en-US", include_str!("../i18n/en-US.yaml")),
        ("es-ES", include_str!("../i18n/es-ES.yaml")),
    ] {
        let messages: HashMap<String, String> =
            serde_yaml::from_str(source).expect("valid library translations");
        env.i18n.add_bundle(TranslationBundle {
            locale: Locale::from(locale),
            messages,
        });
    }
    env
}

pub fn sync_env(state: &crate::app::LibraryState, env: &mut Env) {
    env.locale = state.locale.clone();
}
{"id":"fission-tabs-1","index":6,"label":"src/lib.rs","value":"src-lib-rs"}
pub mod app;
mod i18n;

use app::{LibraryLoanDesk, LibraryState};
use fission::prelude::*;

#[cfg(not(any(target_arch = "wasm32", target_os = "android", target_os = "ios")))]
pub fn run_desktop() -> anyhow::Result<()> {
    DesktopApp::<LibraryState, _>::new(LibraryLoanDesk)
        .with_env(i18n::create_env())
        .with_sync_env(i18n::sync_env)
        .run()
}

#[cfg(any(target_os = "android", target_os = "ios"))]
pub fn run_mobile() -> anyhow::Result<()> {
    MobileApp::<LibraryState, _>::new(LibraryLoanDesk)
        .with_env(i18n::create_env())
        .with_sync_env(i18n::sync_env)
        .run()
}

#[cfg(target_os = "android")]
#[no_mangle]
fn android_main(app_handle: AndroidApp) {
    let _ = MobileApp::<LibraryState, _>::new(LibraryLoanDesk)
        .with_env(i18n::create_env())
        .with_sync_env(i18n::sync_env)
        .run_with_android_app(app_handle);
}

#[cfg(target_arch = "wasm32")]
#[wasm_bindgen::prelude::wasm_bindgen(start)]
pub fn run_web() -> Result<(), wasm_bindgen::JsValue> {
    console_error_panic_hook::set_once();
    WebApp::<LibraryState, _>::new(LibraryLoanDesk)
        .with_env(i18n::create_env())
        .with_sync_env(i18n::sync_env)
        .run()
        .map_err(|error| wasm_bindgen::JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1","index":7,"label":"preview/lib.rs","value":"preview-lib-rs"}
mod app;
mod i18n;

use fission::prelude::*;
use wasm_bindgen::prelude::*;

#[wasm_bindgen(start)]
pub fn run() -> Result<(), JsValue> {
    console_error_panic_hook::set_once();
    WebApp::<app::LibraryState, _>::new(app::LibraryLoanDesk)
        .with_env(i18n::create_env())
        .with_sync_env(i18n::sync_env)
        .mount("#fission-web-mount")
        .run()
        .map_err(|error| JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1","index":8,"label":"i18n/en-US.yaml","value":"i18n-en-us-yaml"}
library.heading: "Library returns desk"
library.session: "Record loans and returns for this session. No library service is connected and reloading clears the records."
library.title: "Book title"
library.reader: "Borrower's name"
library.add: "Record loan"
library.borrower: "Borrowed by {name}"
library.returned: "Returned"
library.on_loan: "On loan"
library.return: "Mark returned"
library.active_total: "On loan: {count}"
library.returned_total: "Recorded returns: {count}"
library.hide_returns: "Hide returned loans"
library.show_returns: "Include returned loans"
library.empty: "No loans match this view. Record a loan or include returned loans."
library.confirmation: "Return recorded: {title}"
language.english: "English"
language.spanish: "Español"
{"id":"fission-tabs-1","index":9,"label":"i18n/es-ES.yaml","value":"i18n-es-es-yaml"}
library.heading: "Mostrador de devoluciones"
library.session: "Registra préstamos y devoluciones para esta sesión. No hay un servicio conectado y recargar borra los registros."
library.title: "Título del libro"
library.reader: "Nombre del lector"
library.add: "Registrar préstamo"
library.borrower: "Prestado a {name}"
library.returned: "Devuelto"
library.on_loan: "Prestado"
library.return: "Registrar devolución"
library.active_total: "Préstamos activos: {count}"
library.returned_total: "Devoluciones registradas: {count}"
library.hide_returns: "Ocultar préstamos devueltos"
library.show_returns: "Incluir préstamos devueltos"
library.empty: "No hay préstamos en esta vista. Registra uno o incluye los devueltos."
library.confirmation: "Devolución registrada: {title}"
language.english: "Inglés"
language.spanish: "Español"
{"id":"fission-tabs-1"}
Enter two different loans and mark one returned. The active total must fall by one and the return total rise by one. Include returned loans to find the record again. Duplicate book titles are valid: each loan has its own ID, so one title must not select every matching record.
Show the app preview
Hide the app preview

2. Keep presentation state from becoming domain data

Compose's state section creates retained local state; it is not an ordinary mutable field on a freshly constructed widget. Here it remembers the unfinished title, borrower and filter while this desk remains mounted. None of those values claims that a loan has been recorded.
props has a different role. LoanCard receives its loan ID from the parent and reads the current record from shared state. Its action captures that small identifier rather than a second copy of the loan. The row does not keep a local returned flag which could disagree with the summary.
The stable key associates a card with its loan during reordering. It does not promise to retain local state after a widget is removed. Completion is safe when the filter hides a row because it belongs to LibraryState, not because the key secretly persists an unmounted card.
Hide returns, record another loan, then include returns again. The original return must remain recorded. Change the filter while there is text in the entry form: the filter should not create a loan or clear the draft.
Show the app preview
Hide the app preview

3. Test the transition and then the interface

cargo test
fission doctor ios --project-dir .
fission devices --project-dir .
fission run --target ios --project-dir .
fission test --target ios --project-dir .
The included tests check that a return changes the intended record once and that invalid entry does not consume an ID. Run them before driving the actual screen. They do not prove the action is connected to the right row, so repeat the add, return and filter sequence in the simulator too.
Use the simulator guide for selection. Check long titles and both languages on a narrow phone; every action must remain reachable. The generated host test establishes launch, not these state transitions or the visual result.
Application state is shared, not automatically durable. This example is explicitly session-scoped and has no library server or disk persistence. A production library would obtain records from its service and enforce authorization there; Fission Store is available when local data must survive restart.