working use_cookie hook

This commit is contained in:
2025-07-15 13:45:22 +02:00
parent 1cb0b44510
commit 4a24db0639
3 changed files with 37 additions and 3 deletions
+28 -1
View File
@@ -1,3 +1,5 @@
use dioxus::prelude::*;
use std::str::FromStr;
use wasm_bindgen::JsCast;
use web_sys::{window, HtmlDocument};
@@ -36,6 +38,31 @@ pub fn get_cookie(name: &str) -> Option<String> {
None
}
pub fn use_cookie<T: FromStr + Default + std::fmt::Display + 'static>(
name: &str,
default: fn() -> T,
) -> Signal<T> {
let name = name.to_string();
let signal = use_signal(default);
use_effect({
let mut signal = signal.clone();
move || {
if let Some(c) = get_cookie(&name) {
if let Ok(cv) = T::from_str(&c) {
signal.set(cv);
}
}
}
});
signal
}
pub fn redirect(target: &str) {
web_sys::window().unwrap().location().set_href(target).unwrap();
web_sys::window()
.unwrap()
.location()
.set_href(target)
.unwrap();
}