use_shared_state brakes the app on write() #1730
Replies: 1 comment
-
First, use shared state is reactive. If you write to the shared state it will rerun any component that use that state. That means if you have a component like this you can cause an infinite loop: fn MyComp(cx: Scope) -> Element {
// This makes MyComp rerun every time AuthState is written to
let app_state = use_shared_state::<AuthState>(cx).unwrap();
// Then we write to AuthState, which causes MyComp to rerun, which triggers a write, causing a rerun, etc.
app_state.write().name = "Joe".to_string();// BRAKES HERE
todo!()
} If you want to only write to the state the first time you render MyComp, you could write to it inside of a use_hook closure which only runs the first time the component runs. When you try to write to the state inside of the closure here you might have another borrow that is already held (maybe in an async task?): on_btn_click: move |_| {app_state.write().name = "Joe".to_string();},// BRAKES HERE Use shared state uses RefCell internally. That means that you can't hold the return value from |
Beta Was this translation helpful? Give feedback.
-
Hi!
Trying to write desktop app and using shared state.
Have created struct:
#[derive(Debug, Serialize, Deserialize)]
pub struct AuthState {
pub name: String,
pub pin: String,
pub location: String,
pub is_auth: bool,
}
In app component:
use_shared_state_provider(cx, || state::auth_state::AuthState::default());
Try to use it in nested component:
let app_state = use_shared_state::<AuthState>(cx).unwrap();
// app_state.write().name = "Joe".to_string();// BRAKES HERE
cx.render(rsx! {
AuthForm{
on_btn_click: move |_| {app_state.write().name = "Joe".to_string();},// BRAKES HERE
},
p{
"{app_state.read().name}"// WORKING GOOD
}
})
}
When i press the button, app_state.write().name changes the name, but app brakes down in a moment.
At the end, HTML in web-view have emty main:
<div id=main></div>
And url changes from:
dioxus.index.html/
to:
dioxus.index.html/?
What's wrong?
Windows 11.
Full project: https://github.com/antongum/kiss_desktop
Beta Was this translation helpful? Give feedback.
All reactions