I am working on a simple application using the Leptos framework which updates a counter. I have cloned a ReadSignal and its corresponding setter function using .clone(). However, I noticed that when I update the original and the cloned signals, they both increment the same value.
#[component]
fn App(cx: Scope) -> impl IntoView {
let (count, set_count) = create_signal(cx, 0);
let dup_count = count.clone();
let dup_set = set_count.clone();
view! { cx,
<div>
<button
on:click=move |_| {
set_count.update(|n| *n += 1);
dup_set.update(|n| *n += 2);
}
>
"Click me: "
{count.get()}
</button>
<div>{count}</div>
<div>{dup_count}</div>
<ProgressBar progress=count />
<ProgressBar progress=dup_count />
</div>
}
}
I am trying to better understand Signals and the different methods in Leptos. I would love some explanations to deepen my understanding. Thank you in advance!
Signals work in a similar way to channels. A pair of
WriteSignalandReadSignalare always connected to each other, as are their clones. This means that you can update the same signal from multiple places by cloning aWriteSignaland react to the same signal from multiple places by cloning aReadSignal.If you want to make a new
WriteSignalwhich is not connected to the originalReadSignalthen you need to create it from scratch withcreate_signal.