#Storing language in client's browser storage

1 messages · Page 1 of 1 (latest)

untold wagon
#

Maybe i'm missing something obvious.
I got these 3 component's

fn HomeWithoutLanguage() -> Element {
    let language = use_signal(|| get_language());
    rsx! {
        Home { language: language }
    }
}

#[component]
fn HomeEn() -> Element {
    rsx! {
        Home { language: "en" }
    }
}
#[component]
fn HomeTr() -> Element {
    rsx! {
        Home { language: "tr" }
    }
}
#[component]
fn HomeRu() -> Element {
    rsx! {
        Home { language: "ru" }
    }
}```

And two public functions:
```use web_sys;

pub fn save_language(lang: &str) {
    if let Ok(Some(storage)) = web_sys::window()
        .unwrap()
        .local_storage()
    {
        let _ = storage.set_item("language", lang);
    }
}

pub fn get_language() -> String {
    web_sys::window()
        .unwrap()
        .local_storage()
        .ok()
        .flatten()
        .and_then(|storage| storage.get_item("language").ok().flatten())
        .unwrap_or_else(|| "en".into())
}
#

When one of those functions being called im getting these error stacktrace:

[server] cannot access imported statics on non-wasm targets```
And big continutaion.

I guess im getting this error because this client-based code is called in server, but im not sure.
These are my dependencies:
```[dependencies]
dioxus = { version = "0.6.3", features = ["router", "fullstack"] }
dioxus-sdk = { version = "=0.6.0", features = ["channel"] }
gloo-timers = "0.3.0"
chrono = "0.4.39"
lazy_static = "1.5.0"
num-format = "0.4.4"
reqwest = { version = "0.12.12", features = ["json", "rustls-tls", "charset", "http2", "macos-system-configuration"], default-features = false }
serde = "1.0.217"
cached = { version = "0.54.0", features = ["async"] }
web-sys = { version = "0.3.77", features = ["Window", "Storage"] }
dioxus-i18n = "0.4.2"```

Maybe there is a more proper way of dealing with storing language or anything else
left viper
#

I can't help you with websys, but I've got it working with the dioxus-sdk's use_synced_storage. It can be enabled with the storage feature.

Since you are using fullstack though, you have to make sure that the localstorage is only queried when we are on the client and not on the server. One way to do this is to wrap the code that redirects to the correct language page in use_effect, which will only get executed on the client side, where we can actually get the value from localstorage