Leptos-Use Guide

Encoding and Decoding Data

Several functions encode and decode data for storing it and/or sending it over the network. To do this, codecs from the crate codee are used. They implement the traits Encoder with the method encode and Decoder with the method decode.

There are two types of codecs: One that encodes as binary data (Vec[u8]) and another type that encodes as strings (String). There is also an adapter Base64 that can be used to wrap a binary codec and make it a string codec by representing the binary data as a base64 string.

Please check the documentation of codee for more details and a list of all available codecs.

Example

In this example, a codec is given to use_cookie that stores data as a string in the JSON format. Since cookies can only store strings, we have to use string codecs here.

use leptos::*;
use leptos_use::use_cookie;
use serde::{Deserialize, Serialize};
use codee::string::JsonCodec;

#[component]
pub fn App(cx: Scope) -> impl IntoView {
#[derive(Serialize, Deserialize, Clone)]
struct MyState {
    chicken_count: i32,
    egg_count: i32,
}

let (cookie, set_cookie) = use_cookie::<MyState, JsonCodec>("my-state-cookie");    
view! {}
}

Custom Codecs

If you don't find a suitable codec for your needs, you can implement your own; it's straightforward! If you want to create a string codec, you can look at JsonSerdeCodec. In case it's a binary codec, have a look at BincodeSerdeCodec.

Versioning

For a discussion on how to implement versioning please refer to the relevant section in the docs for codee.