dioxus_use_storage/hooks/use_local_storage/
mod.rs

1mod display;
2mod iter;
3
4use super::*;
5
6/// Local storage effect handler
7pub struct UseLocalStorage {
8    data: Rc<RefCell<UseStorageData>>,
9    listen_storage: Option<EventListener>,
10}
11
12impl UseStorageBuilder {
13    /// hooks for window's size with config
14    ///
15    /// # Arguments
16    ///
17    /// returns: [`WindowSize`]
18    ///
19    /// # Examples
20    ///
21    /// ```
22    /// use dioxus::prelude::*;
23    /// use dioxus_use_storage::use_local_storage;
24    ///
25    /// fn App(cx: Scope) -> Element {
26    ///     let hook = use_local_storage(&cx);
27    ///
28    ///     cx.render(rsx!(
29    ///         h1 { "Local Storage: {hook}" }
30    ///     ))
31    /// }
32    /// ```
33    pub fn use_local_storage<'a>(&self, cx: &'a ScopeState) -> &'a mut UseLocalStorage {
34        let hook = UseLocalStorage::new(cx);
35        cx.use_hook(|| hook)
36    }
37}
38
39impl UseLocalStorage {
40    fn new(cx: &ScopeState) -> Self {
41        match Self::try_new(cx) {
42            Some(s) => s,
43            None => {
44                warn!("Local Storage Listener Initializing failed at {}!", cx.scope_id().0);
45                Self::default()
46            }
47        }
48    }
49    fn try_new(cx: &ScopeState) -> Option<Self> {
50        let window = window()?;
51        let storage = window.local_storage().ok()??;
52        let data = UseStorageData::new(Some(storage));
53        let listen_storage = on_storage(cx, &window, &data);
54        Some(Self { data, listen_storage: Some(listen_storage) })
55    }
56}
57
58impl UseLocalStorage {
59    /// get value of given key
60    #[inline]
61    pub fn get(&self, key: &str) -> Option<String> {
62        self.data.borrow().get(key)
63    }
64    /// get (key, value) at index i
65    #[inline]
66    pub fn get_index(&self, index: usize) -> Option<(String, String)> {
67        self.data.borrow().get_index(index)
68    }
69    /// insert new value with key, return false if failed to run
70    #[inline]
71    pub fn insert(&self, key: &str, value: &str) -> bool {
72        self.data.borrow().insert(key, value).is_some()
73    }
74    /// insert value with given key, return false if failed to run
75    #[inline]
76    pub fn remove(&self, key: &str) -> bool {
77        self.data.borrow().remove(key).is_some()
78    }
79    /// count items in storage
80    #[inline]
81    pub fn len(&self) -> usize {
82        self.data.borrow().len().unwrap_or_default()
83    }
84    /// clear all value in storage, return false if failed to run
85    #[inline]
86    pub fn clear(&self) -> bool {
87        self.data.borrow().clear().is_some()
88    }
89}