store

Attribute Macro store 

Source
#[store]
Expand description

§#[store]

The store attribute macro is used to create an extension trait for store implementations. The extension traits lets you add methods to the store even though the type is not defined in your crate.

§Arguments

  • pub: Makes the generated extension trait public. If not provided, the trait will be private.
  • name = YourExtensionName: The name of the extension trait. If not provided, it will be generated based on the type name.

§Bounds

The generated extension trait will have bounds on the lens generic parameter to ensure it implements Readable or Writable as needed.

  • If a method accepts &self, the lens will require Readable which lets you read the value of the store.
  • If a method accepts &mut self, the lens will require Writable which lets you change the value of the store.

§Example

use dioxus::prelude::*;
use dioxus_stores::*;

#[derive(Store)]
struct TodoItem {
    checked: bool,
    contents: String,
}

// You can use the store attribute macro to add methods to your stores
#[store]
impl<Lens> Store<TodoItem, Lens> {
   // Since this method takes &mut self, the lens will require Writable automatically. It cannot be used
   // with ReadStore<TodoItem>
   fn toggle_checked(&mut self) {
       self.checked().toggle();
   }

   // Since this method takes &self, the lens will require Readable automatically
   fn checked_contents(&self) -> Option<String> {
       self.checked().cloned().then(|| self.contents().to_string())
   }
}

let mut store = use_store(|| TodoItem {
    checked: false,
    contents: "Learn about stores".to_string(),
});

// You can use the methods defined in the extension trait
store.toggle_checked();
let contents: Option<String> = store.checked_contents();