Struct leptos_use::utils::JsonCodec

source ·
pub struct JsonCodec;
Expand description

A codec for storing JSON messages that relies on serde_json to parse.

§Example

// Primitive types:
let (get, set, remove) = use_local_storage::<i32, JsonCodec>("my-key");

// Structs:
#[derive(Serialize, Deserialize, Clone, Default, PartialEq)]
pub struct MyState {
    pub hello: String,
}
let (get, set, remove) = use_local_storage::<MyState, JsonCodec>("my-struct-key");

§Versioning

If the JSON decoder fails, the storage hook will return T::Default dropping the stored JSON value. See Codec for general information on codec versioning.

§Rely on serde

This codec uses serde_json under the hood. A simple way to avoid complex versioning is to rely on serde’s field attributes such as serde(default) and serde(rename = "...").

§String replacement

Previous versions of leptos-use offered a merge_defaults fn to rewrite the encoded value. This is possible by wrapping the codec but should be avoided.

#[derive(Serialize, Deserialize, Clone, Default, PartialEq)]
pub struct MyState {
    pub hello: String,
    pub greeting: String,
}

#[derive(Clone, Default)]
pub struct MyStateCodec();
impl StringCodec<MyState> for MyStateCodec {
    type Error = serde_json::Error;

    fn encode(&self, val: &MyState) -> Result<String, Self::Error> {
        serde_json::to_string(val)
    }

    fn decode(&self, stored_value: String) -> Result<MyState, Self::Error> {
        let default_value = MyState::default();
        let rewritten = if stored_value.contains(r#""greeting":"#) {
            stored_value
        } else {
            // add "greeting": "Hello" to the string
            stored_value.replace("}", &format!(r#""greeting": "{}"}}"#, default_value.greeting))
        };
        serde_json::from_str(&rewritten)
    }
}

let (get, set, remove) = use_local_storage::<MyState, MyStateCodec>("my-struct-key");

§Transform a JsValue

A better alternative to string replacement might be to parse the JSON then transform the resulting JsValue before decoding it to to your struct again.

#[derive(Serialize, Deserialize, Clone, Default, PartialEq)]
pub struct MyState {
    pub hello: String,
    pub greeting: String,
}

#[derive(Clone, Default)]
pub struct MyStateCodec();
impl StringCodec<MyState> for MyStateCodec {
    type Error = serde_json::Error;

    fn encode(&self, val: &MyState) -> Result<String, Self::Error> {
        serde_json::to_string(val)
    }

    fn decode(&self, stored_value: String) -> Result<MyState, Self::Error> {
        let mut val: serde_json::Value = serde_json::from_str(&stored_value)?;
        // add "greeting": "Hello" to the object if it's missing
        if let Some(obj) = val.as_object_mut() {
            if !obj.contains_key("greeting") {
               obj.insert("greeting".to_string(), json!("Hello"));
            }
            serde_json::from_value(val)
        } else {
            Ok(MyState::default())
        }
    }
}

let (get, set, remove) = use_local_storage::<MyState, MyStateCodec>("my-struct-key");

Trait Implementations§

source§

impl Clone for JsonCodec

source§

fn clone(&self) -> JsonCodec

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Default for JsonCodec

source§

fn default() -> JsonCodec

Returns the “default value” for a type. Read more
source§

impl PartialEq for JsonCodec

source§

fn eq(&self, other: &JsonCodec) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<T: Serialize + DeserializeOwned> StringCodec<T> for JsonCodec

§

type Error = Error

The error type returned when encoding or decoding fails.
source§

fn encode(&self, val: &T) -> Result<String, Self::Error>

Encodes a value to a string.
source§

fn decode(&self, str: String) -> Result<T, Self::Error>

Decodes a string to a value. Should be able to decode any string encoded by [encode].
source§

impl Copy for JsonCodec

source§

impl StructuralPartialEq for JsonCodec

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> IntoEither for T

source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more