Merge branch 'main' into resource-dependancies

This commit is contained in:
Evan Almloff committed 2024-03-13 10:03:44 -05:00
commit 80aeba30c7
18 files changed
+292 -86

No files matched your search

+5 -1
View File
@@ -15,6 +15,9 @@ pub fn try_use_context<T: 'static + Clone>() -> Option<T> {
///
/// Does not regenerate the value if the value is changed at the parent.
/// ```rust
/// # use dioxus::prelude::*;
/// # #[derive(Clone, Copy, PartialEq, Debug)]
/// # enum Theme { Dark, Light }
/// fn Parent() -> Element {
/// use_context_provider(|| Theme::Dark);
/// rsx! { Child {} }
@@ -38,6 +41,7 @@ pub fn use_context<T: 'static + Clone>() -> T {
/// drilling, using a context provider with a Signal inside is a good way to provide global/shared
/// state in your app:
/// ```rust
/// # use dioxus::prelude::*;
///fn app() -> Element {
/// use_context_provider(|| Signal::new(0));
/// rsx! { Child {} }
@@ -45,7 +49,7 @@ pub fn use_context<T: 'static + Clone>() -> T {
/// // This component does read from the signal, so when the signal changes it will rerun
///#[component]
///fn Child() -> Element {
/// let signal: Signal<i32> = use_context();
/// let mut signal: Signal<i32> = use_context();
/// rsx! {
/// button { onclick: move |_| signal += 1, "increment context" }
/// p {"{signal}"}
+1
View File
@@ -9,6 +9,7 @@ use dioxus_signals::*;
/// effects will always run after first mount and then whenever the signal values change
/// If the use_effect call was skipped due to an early return, the effect will no longer activate.
/// ```rust
/// # use dioxus::prelude::*;
/// fn app() -> Element {
/// let mut count = use_signal(|| 0);
/// //the effect runs again each time count changes
+2
View File
@@ -13,6 +13,8 @@ use std::ops::Deref;
/// `use_future` **won't return a value**.
/// If you want to return a value from a future, use `use_resource` instead.
/// ```rust
/// # use dioxus::prelude::*;
/// # use std::time::Duration;
/// fn app() -> Element {
/// let mut count = use_signal(|| 0);
/// let mut running = use_signal(|| true);
+29 -10
View File
@@ -15,16 +15,28 @@ use std::{cell::Cell, future::Future, rc::Rc};
/// Similar to `use_future` but `use_resource` returns a value.
/// See [`Resource`] for more details.
/// ```rust
///fn app() -> Element {
/// let country = use_signal(|| WeatherLocation {
/// city: "Berlin".to_string(),
/// country: "Germany".to_string(),
/// coordinates: (52.5244, 13.4105)
/// });
/// # use dioxus::prelude::*;
/// # #[derive(Clone)]
/// # struct WeatherLocation {
/// # city: String,
/// # country: String,
/// # coordinates: (f64, f64),
/// # }
/// # async fn get_weather(location: &WeatherLocation) -> Result<String, String> {
/// # Ok("Sunny".to_string())
/// # }
/// # #[component]
/// # fn WeatherElement (weather: String ) -> Element { rsx! { p { "The weather is {weather}" } } }
/// fn app() -> Element {
/// let country = use_signal(|| WeatherLocation {
/// city: "Berlin".to_string(),
/// country: "Germany".to_string(),
/// coordinates: (52.5244, 13.4105)
/// });
///
/// // Because the resource's future subscribes to `country` by reading it (`country.read()`),
/// // every time `country` changes the resource's future will run again and thus provide a new value.
/// let current_weather = use_resource(move || async move { get_weather(&country.read().clone()).await });
/// let current_weather = use_resource(move || async move { get_weather(&country()).await });
///
/// rsx! {
/// // the value of the resource can be polled to
@@ -32,9 +44,9 @@ use std::{cell::Cell, future::Future, rc::Rc};
/// // finished (Some(Ok(_)), errored Some(Err(_)),
/// // or is still running (None)
/// match current_weather.value() {
/// Some(Ok(weather)) => WeatherElement { weather },
/// Some(Err(e)) => p { "Loading weather failed, {e}" }
/// None => p { "Loading..." }
/// Some(Ok(weather)) => rsx! { WeatherElement { weather } },
/// Some(Err(e)) => rsx! { p { "Loading weather failed, {e}" } },
/// None => rsx! { p { "Loading..." } }
/// }
/// }
///}
@@ -107,6 +119,13 @@ pub struct Resource<T: 'static> {
callback: UseCallback<Task>,
}
impl<T> Clone for Resource<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> Copy for Resource<T> {}
/// A signal that represents the state of the resource
// we might add more states (panicked, etc)
#[derive(Clone, Copy, PartialEq, Hash, Eq, Debug)]
+73
View File
@@ -0,0 +1,73 @@
#[tokio::test]
async fn memo_updates() {
use std::cell::RefCell;
use dioxus::prelude::*;
thread_local! {
static VEC_SIGNAL: RefCell<Option<Signal<Vec<usize>, SyncStorage>>> = RefCell::new(None);
}
fn app() -> Element {
let mut vec = use_signal_sync(|| vec![0, 1, 2]);
// Signals should update if they are changed from another thread
use_hook(|| {
VEC_SIGNAL.with(|cell| {
*cell.borrow_mut() = Some(vec);
});
std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_millis(100));
vec.push(5);
});
});
let len = vec.len();
let len_memo = use_memo(move || vec.len());
// Make sure memos that update in the middle of a component work
if generation() < 2 {
vec.push(len);
}
// The memo should always be up to date
assert_eq!(vec.len(), len_memo());
rsx! {
for i in 0..len {
Child {
index: i,
vec,
}
}
}
}
#[component]
fn Child(index: usize, vec: Signal<Vec<usize>, SyncStorage>) -> Element {
// This memo should not rerun after the element is removed
let item = use_memo(move || vec.read()[index]);
rsx! {
div { "Item: {item}" }
}
}
let mut dom = VirtualDom::new(app);
dom.rebuild_in_place();
let mut signal = VEC_SIGNAL.with(|cell| (*cell.borrow()).unwrap());
// Wait for the signal to update
for _ in 0..3 {
dom.wait_for_work().await;
dom.render_immediate(&mut dioxus::dioxus_core::NoOpMutations);
println!("Signal: {signal:?}");
}
assert_eq!(signal(), vec![0, 1, 2, 3, 4, 5]);
// Remove each element from the vec
for _ in 0..6 {
signal.pop();
dom.wait_for_work().await;
dom.render_immediate(&mut dioxus::dioxus_core::NoOpMutations);
println!("Signal: {signal:?}");
}
}