Synphonyte / leptos-use

Collection of essential Leptos utilities inspired by React-Use / VueUse / SolidJS-USE
https://leptos-use.rs/
Apache License 2.0
309 stars 66 forks source link

use_cookie causes panic #127

Closed GarrettFleischer closed 2 months ago

GarrettFleischer commented 2 months ago

I'm trying to write a logged in wrapper that uses the following cookie. I seem to be able to set the cookie just fine from inside a server function, but adding the following code as a component causes this error. I am using nightly rust with leptos if that matters.

thread 'main' panicked at ...\.cargo\registry\src\index.crates.io-6f17d22bba15001f\js-sys-0.3.69\src\lib.rs:6013:9:
cannot call wasm-bindgen imported functions on non-wasm targets
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread 'main' panicked at /rustc/ab5bda1aa70f707014e2e691e43bc37a8819252a\library\std\src\thread\local.rs:260:26:
cannot access a Thread Local Storage value during or after destruction: AccessError
fatal runtime error: thread local panicked on drop
#[component]
pub fn AuthRequired(children: Children) -> impl IntoView {
    let (cookie, _) = use_cookie::<String, FromToStringCodec>("token");

    cookie.with(move |jwt| match jwt {
        Some(_) => children().into_view(),
        _ => view! { <Redirect path="/login"/> },
    })
}

The crash happens so long as use_cookie is anywhere in any component. I can comment out the cookie.with(...) code and the error still occurs until I also comment out use_cookie

maccesch commented 2 months ago

Hm... do you have SSR correctly configured? Could you send your Cargo.toml?

GarrettFleischer commented 2 months ago
[package]
name = "emp"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib", "rlib"]

[dependencies]
axum = { version = "0.7", optional = true }
console_error_panic_hook = "0.1"
leptos = { version = "0.6", features = ["nightly"] }
leptos_axum = { version = "0.6", optional = true }
leptos_meta = { version = "0.6", features = ["nightly"] }
leptos_router = { version = "0.6", features = ["nightly"] }
tokio = { version = "1", features = ["macros", "rt-multi-thread"], optional = true }
tower = { version = "0.4", optional = true }
tower-http = { version = "0.5", features = ["fs"], optional = true }
wasm-bindgen = "=0.2.92"
thiserror = "1"
tracing = { version = "0.1", optional = true }
http = "1" 
serde = { version = "1", features = ["derive"] }
serde_json = "1"
surrealdb = { version = "1.5.3", optional = true}
bcrypt = {version = "0.15.1", optional =  true}
chrono = {version = "0.4", optional = true}
cfg-if = "1.0.0"
leptos-use = "0.10"
tower-sessions = {version = "0.12", optional = true}
dotenv = {version = "*", optional = true}
# tower-cookies = "0.10.0"

[features]
hydrate = ["leptos/hydrate", "leptos_meta/hydrate", "leptos_router/hydrate"]
ssr = [
    "dep:axum",
    "dep:tokio",
    "dep:tower",
    "dep:tower-http",
    "dep:leptos_axum",
    "leptos/ssr",
    "leptos_meta/ssr",
    "leptos_router/ssr",
    "dep:tracing",
    "dep:surrealdb",
    "dep:bcrypt",
    "dep:chrono",
    "dep:tower-sessions",
    "dep:dotenv"
]

# Defines a size-optimized profile for the WASM bundle in release mode
[profile.wasm-release]
inherits = "release"
opt-level = 'z'
lto = true
codegen-units = 1
panic = "abort"

[package.metadata.leptos]
# The name used by wasm-bindgen/cargo-leptos for the JS/WASM bundle. Defaults to the crate name
output-name = "emp"

# The site root folder is where cargo-leptos generate all output. WARNING: all content of this folder will be erased on a rebuild. Use it in your server setup.
site-root = "target/site"

# The site-root relative folder where all compiled output (JS, WASM and CSS) is written
# Defaults to pkg
site-pkg-dir = "pkg"

# [Optional] The source CSS file. If it ends with .sass or .scss then it will be compiled by dart-sass into CSS. The CSS is optimized by Lightning CSS before being written to <site-root>/<site-pkg>/app.css
style-file = "style/style-file.css"

# Activates the tailwind build
tailwind-input-file = "style/tailwind.css"
tailwind-config-file = "tailwind.config.js"

# Assets source dir. All files found here will be copied and synchronized to site-root.
# The assets-dir cannot have a sub directory with the same name/path as site-pkg-dir.
#
# Optional. Env: LEPTOS_ASSETS_DIR.
assets-dir = "public"

# The IP and port (ex: 127.0.0.1:3000) where the server serves the content. Use it in your server setup.
site-addr = "127.0.0.1:3000"

# The port to use for automatic reload monitoring
reload-port = 3001

# [Optional] Command to use when running end2end tests. It will run in the end2end dir.
#   [Windows] for non-WSL use "npx.cmd playwright test"
#   This binary name can be checked in Powershell with Get-Command npx
end2end-cmd = "npx playwright test"
end2end-dir = "end2end"

#  The browserlist query used for optimizing the CSS.
browserquery = "defaults"

# The environment Leptos will run in, usually either "DEV" or "PROD"
env = "DEV"

# The features to use when compiling the bin target
#
# Optional. Can be over-ridden with the command line parameter --bin-features
bin-features = ["ssr"]

# If the --no-default-features flag should be used when compiling the bin target
#
# Optional. Defaults to false.
bin-default-features = false

# The features to use when compiling the lib target
#
# Optional. Can be over-ridden with the command line parameter --lib-features
lib-features = ["hydrate"]

# If the --no-default-features flag should be used when compiling the lib target
#
# Optional. Defaults to false.
lib-default-features = false

# The profile to use for the lib target when compiling for release
#
# Optional. Defaults to "release".
lib-profile-release = "wasm-release"
GarrettFleischer commented 2 months ago

well, I'm at a complete loss now.

I read the docs for use_cookie again and it said to enable the feature "axum", but when I do that like so leptos-use = {version = "0.10", features = ["axum"]} I get this compilation error compile_error!("Only features sync,macros,io-util,rt,time are supported on wasm.");

Edit: Adding this to the ssr in cargo.toml compiles, but the same crash happens in the component when I try to use_cookie

ssr = [
    ...
    "leptos-use/axum",
]
GarrettFleischer commented 2 months ago

I'm trying to fake it by wrapping it in a call to a server function, but I can't seem to figure out how to use the getter inside a server function. If I try cookie.get() or cookie.with() I get "Send is not implemented" compiler error.

#[server(LoggedIn, "/api")]
pub async fn logged_in() -> Result<(), ServerFnError> {
    let (cookie, _) = use_cookie::<String, FromToStringCodec>("token");
    let result = cookie.get();

   // ....
}
future cannot be sent between threads safely
the trait `Send` is not implemented for `(dyn std::ops::Fn() -> std::option::Option<std::string::String> + 'static)`, which is required by `{async block
GarrettFleischer commented 2 months ago

leptos-use = {version = "0.10", features = ["ssr"]}

That fixes the crash in the component, but if I add the "axum" feature as well I still get this compiler error compile_error!("Only features sync,macros,io-util,rt,time are supported on wasm.");

maccesch commented 2 months ago

I guess you didn't read https://leptos-use.rs/server_side_rendering.html? 😂

Do this:


[dependencies]
# ...
leptos-use = "0.10"

[features]
# ...
ssr = [
    # ...
    "leptos-use/ssr",
    "leptos-use/axum",
]