Function leptos_use::storage::use_storage

source ·
pub fn use_storage<T, C>(
    storage_type: StorageType,
    key: impl AsRef<str>
) -> (Signal<T>, WriteSignal<T>, impl Fn() + Clone)
where T: Default + Clone + PartialEq, C: StringCodec<T> + Default,
Expand description

Reactive Storage.

The function returns a triplet (read_signal, write_signal, delete_from_storage_fn).

§Demo

Link to Demo

§Usage

Pass a StorageType to determine the kind of key-value browser storage to use. The specified key is where data is stored. All values are stored as UTF-16 strings which is then encoded and decoded via the given [Codec]. This value is synced with other calls using the same key on the smae page and across tabs for local storage. See UseStorageOptions to see how behaviour can be further customised.

See StringCodec for more details on how to handle versioning — dealing with data that can outlast your code.

To use the [JsonCodec], you will need to add the "serde" feature to your project’s Cargo.toml. To use [ProstCodec], add the feature "prost".

§Example

// Binds a struct:
let (state, set_state, _) = use_local_storage::<MyState, JsonCodec>("my-state");

// Binds a bool, stored as a string:
let (flag, set_flag, remove_flag) = use_session_storage::<bool, FromToStringCodec>("my-flag");

// Binds a number, stored as a string:
let (count, set_count, _) = use_session_storage::<i32, FromToStringCodec>("my-count");
// Binds a number, stored in JSON:
let (count, set_count, _) = use_session_storage::<i32, JsonCodec>("my-count-kept-in-js");

// Bind string with SessionStorage stored in ProtoBuf format:
let (id, set_id, _) = use_storage::<String, ProstCodec>(
    StorageType::Session,
    "my-id",
);

// Data stored in JSON must implement Serialize, Deserialize.
// And you have to add the feature "serde" to your project's Cargo.toml
#[derive(Serialize, Deserialize, Clone, PartialEq)]
pub struct MyState {
    pub hello: String,
    pub greeting: String,
}

// Default can be used to implement initial or deleted values.
// You can also use a signal via UseStorageOptions::default_value`
impl Default for MyState {
    fn default() -> Self {
        Self {
            hello: "hi".to_string(),
            greeting: "Hello".to_string()
        }
    }
}

§Create Your Own Custom Codec

All you need to do is to implement the StringCodec trait together with Default and Clone.

§Server-Side Rendering

On the server the returned signals will just read/manipulate the initial_value without persistence.