Is it not possible to use the provide_context function within the shell function? #3399
-
I'm trying to make HTML tag attributes reactive, but I'm running into some issues. thread 'main' panicked at src\app.rs:67:10: Is it not possible to use the provide_context function within the shell function? use leptos::prelude::*;
use leptos_meta::{provide_meta_context, MetaTags, Stylesheet, Title};
use leptos_router::{
components::{Route, Router, Routes},
StaticSegment,
};
#[derive(Debug, Clone, Copy)]
pub enum ColorMode {
Light,
Dark,
}
pub fn shell(options: LeptosOptions) -> impl IntoView {
let mode = RwSignal::new(ColorMode::Light);
provide_context(mode);
view! {
<!DOCTYPE html>
<html lang="en" class= move || match mode.get() {
ColorMode::Light => "light",
ColorMode::Dark => "dark"
}>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<AutoReload options=options.clone() />
<HydrationScripts options/>
<MetaTags/>
</head>
<body>
<App/>
</body>
</html>
}
}
#[component]
pub fn App() -> impl IntoView {
// Provides context that manages stylesheets, titles, meta tags, etc.
provide_meta_context();
view! {
// injects a stylesheet into the document <head>
// id=leptos means cargo-leptos will hot-reload this stylesheet
<Stylesheet id="leptos" href="/pkg/provide_context_error.css"/>
// sets the document title
<Title text="Welcome to Leptos"/>
<ThemeToggle/>
// content for this welcome page
<Router>
<main>
<Routes fallback=|| "Page not found.".into_view()>
<Route path=StaticSegment("") view=HomePage/>
</Routes>
</main>
</Router>
}
}
#[component]
pub fn ThemeToggle() -> impl IntoView {
let mode = use_context::<RwSignal<ColorMode>>()
.expect("ColorMode signal should be provided in context");
let toggle_mode = move |_| {
mode.update(|current| {
*current = match current {
ColorMode::Light => ColorMode::Dark,
ColorMode::Dark => ColorMode::Light,
}
});
};
view! {
<button class="theme-toggle" on:click=toggle_mode>
{move || match mode.get() {
ColorMode::Light => "Color mode: Light",
ColorMode::Dark => "Color mode: Dark",
}}
</button>
}
}
/// Renders the home page of your application.
#[component]
fn HomePage() -> impl IntoView {
// Creates a reactive value to update the button
let count = RwSignal::new(0);
let on_click = move |_| *count.write() += 1;
view! {
<h1>"Welcome to Leptos!"</h1>
<button on:click=on_click>"Click Me: " {count}</button>
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
The |
Beta Was this translation helpful? Give feedback.
The
shell
only runs on the server, so it won't be provided in the client, which is where you're trying to consume it inThemeToggle
. Why not provide it inApp
instead (and use the<Html/>
component fromleptos_meta
to set it on the<html>
tag)