intendednull / yewdux

Ergonomic state management for Yew applications
https://intendednull.github.io/yewdux/
Apache License 2.0
322 stars 31 forks source link

Suggestion: Provide standard implementations for persisted stores #26

Closed lpotthast closed 2 years ago

lpotthast commented 2 years ago

If we want a store with persistence, going by the current state of the Readme, we always need to implement even the (sane) default implementation that simply deserializes on load and serializes on every change ourself. Something like this: (I changed it slightly, so that it logs an error instead of panicking. Think this is fine here. Don't know what we could otherwise do with the error..)

#[derive(Default, Clone, PartialEq, Debug, Serialize, Deserialize)]
pub struct Theme {
    pub is_dark_mode: bool,
}

impl Store for Theme {
    fn new() -> Self {
        yewdux::storage::load(yewdux::storage::Area::Local)
            .map_err(|error| error!("Unable to load state due to StorageError: {}", error))
            .ok()
            .flatten()
            .unwrap_or_default()
    }

    fn changed(&mut self) {
        if let Some(error) = yewdux::storage::save(self, yewdux::storage::Area::Local).err() {
            error!("Unable to save state due to StorageError: {}", error)
        }
    }
}

I would assume that, at many times, nothing more sophisticated is required and therefore a default (or standard) implementation for the Store trait that provides just something like this should be worth it. Havin the Store macro already, two additional macros named LocalPersistedStore and SessionPersistedStore would do it, letting the user choose the yewdux::storage::Area being used. With a note at the documentation/readme that anything else can and must be implemented manually.

intendednull commented 2 years ago

Yes definitely want an auto impl, maybe something like #[derive(Store(storage = Area::Local))]

Honestly don't have much experience with building macros so this may take some time to implement. Coming as soon as I can figure it out!

intendednull commented 2 years ago

Turns out args like that aren't possible, so maybe something like

#[derive(Store, ..)]
#[store(storage = Area::Local)]
intendednull commented 2 years ago

See new macro attr here https://github.com/intendednull/yewdux/blob/master/examples/persistent/src/main.rs