Improve inline docs (#2460)

Improve inline docs

* improve incorrect event handler return error message

* Improve event handler docs

* document the eval functions

* document spawn and common spawn errors

* fix event handler docs

* add notes about how you use attributes and elements in rsx

* add doc aliases for attributes and events we rename

* add some more aliases for common search terms

* don't doc ignore any public examples in core

* don't ignore public doc examples in ssr

* don't ignore examples in the dioxus package readme

* add a warning when you launch without a renderer enabled

* fix some outdated element docs

* add a bunch of examples to resource

* add notes about desktop events

* add more docs for use_resource

* add on_unimplemented hint to Dependency

* fix some unresolved links

* add examples to each of the router traits

* add not implemented errors for router traits

* add an example to the routable trait

* expand rsx macro docs

* improve memo docs

* update the dioxus readme

* mention dioxus crate features in the docs

* fix a bunch of doc tests

* fix html doc tests

* fix router doc tests

* fix dioxus signals doc tests

* fix dioxus ssr doc tests

* fix use_future example in the hooks cheat sheet

* add a javascript alias for eval

* fix hook explanation values

* remove unused embed-doc-image dependency
This commit is contained in:
Evan Almloff authored and GitHub committed 2024-06-06 18:15:17 -07:00
1 parent 054351139f
commit 0127501dbf
71 files changed
+4132 -1162

No files matched your search

+15 -1
View File
@@ -9,6 +9,7 @@ use dioxus_signals::Writable;
/// There is *currently* no signal tracking on the Callback so anything reading from it will not be updated.
///
/// This API is in flux and might not remain.
#[doc = include_str!("../docs/rules_of_hooks.md")]
pub fn use_callback<O>(f: impl FnMut() -> O + 'static) -> UseCallback<O> {
// Create a copyvalue with no contents
// This copyvalue is generic over F so that it can be sized properly
@@ -35,11 +36,24 @@ pub fn use_callback<O>(f: impl FnMut() -> O + 'static) -> UseCallback<O> {
/// This callback is not generic over a return type so you can hold a bunch of callbacks at once
///
/// If you need a callback that returns a value, you can simply wrap the closure you pass in that sets a value in its scope
#[derive(PartialEq)]
pub struct UseCallback<O: 'static + ?Sized> {
inner: CopyValue<Box<dyn FnMut() -> O>>,
}
impl<O: 'static + ?Sized> PartialEq for UseCallback<O> {
fn eq(&self, other: &Self) -> bool {
self.inner == other.inner
}
}
impl<O: 'static + ?Sized> std::fmt::Debug for UseCallback<O> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("UseCallback")
.field("inner", &self.inner.value())
.finish()
}
}
impl<O: 'static + ?Sized> Clone for UseCallback<O> {
fn clone(&self) -> Self {
Self { inner: self.inner }
+1 -1
View File
@@ -1,5 +1,5 @@
/*
a form of use_state explicitly for map-style collections (BTreeMap, HashMap, etc).
a form of use_signal explicitly for map-style collections (BTreeMap, HashMap, etc).
Why?
---
+6
View File
@@ -6,6 +6,8 @@ use dioxus_core::{
/// Consume some context in the tree, providing a sharable handle to the value
///
/// Does not regenerate the value if the value is changed at the parent.
#[doc = include_str!("../docs/rules_of_hooks.md")]
#[doc = include_str!("../docs/moving_state_around.md")]
#[must_use]
pub fn try_use_context<T: 'static + Clone>() -> Option<T> {
use_hook(|| try_consume_context::<T>())
@@ -29,6 +31,8 @@ pub fn try_use_context<T: 'static + Clone>() -> Option<T> {
/// rsx! { "user using dark mode: {user_theme == Theme::Dark}" }
/// }
/// ```
#[doc = include_str!("../docs/rules_of_hooks.md")]
#[doc = include_str!("../docs/moving_state_around.md")]
#[must_use]
pub fn use_context<T: 'static + Clone>() -> T {
use_hook(|| consume_context::<T>())
@@ -56,6 +60,8 @@ pub fn use_context<T: 'static + Clone>() -> T {
/// }
///}
/// ```
#[doc = include_str!("../docs/rules_of_hooks.md")]
#[doc = include_str!("../docs/moving_state_around.md")]
pub fn use_context_provider<T: 'static + Clone>(f: impl FnOnce() -> T) -> T {
use_hook(|| provide_context(f()))
}
+10 -6
View File
@@ -6,11 +6,11 @@ use std::future::Future;
/// Maintain a handle over a future that can be paused, resumed, and canceled.
///
/// This is an upgraded form of [`use_future`] with an integrated channel system.
/// Specifically, the coroutine generated here comes with an [`UnboundedChannel`]
/// This is an upgraded form of [`crate::use_future()`] with an integrated channel system.
/// Specifically, the coroutine generated here comes with an [`futures_channel::mpsc::UnboundedSender`]
/// built into it - saving you the hassle of building your own.
///
/// Addititionally, coroutines are automatically injected as shared contexts, so
/// Additionally, coroutines are automatically injected as shared contexts, so
/// downstream components can tap into a coroutine's channel and send messages
/// into a singular async event loop.
///
@@ -33,7 +33,7 @@ use std::future::Future;
/// ## UseCallback instead
///
/// However, you must plan out your own concurrency and synchronization. If you
/// don't care about actions in your app being synchronized, you can use [`use_callback`]
/// don't care about actions in your app being synchronized, you can use [`crate::use_callback()`]
/// hook to spawn multiple tasks and run them concurrently.
///
/// ### Notice
@@ -42,7 +42,9 @@ use std::future::Future;
///
/// ## Example
///
/// ```rust, ignore
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// use futures_util::StreamExt;
/// enum Action {
/// Start,
/// Stop,
@@ -63,8 +65,9 @@ use std::future::Future;
/// onclick: move |_| chat_client.send(Action::Start),
/// "Start Chat Service"
/// }
/// })
/// };
/// ```
#[doc = include_str!("../docs/rules_of_hooks.md")]
pub fn use_coroutine<M, G, F>(init: G) -> Coroutine<M>
where
M: 'static,
@@ -96,6 +99,7 @@ where
/// Analagous to use_context_provider and use_context,
/// but used for coroutines specifically
/// See the docs for [`use_coroutine`] for more details.
#[doc = include_str!("../docs/rules_of_hooks.md")]
#[must_use]
pub fn use_coroutine_handle<M: 'static>() -> Coroutine<M> {
use_hook(consume_context::<Coroutine<M>>)
+2 -35
View File
@@ -4,41 +4,8 @@ use futures_util::StreamExt;
use crate::use_callback;
/// `use_effect` will subscribe to any changes in the signal values it captures
/// 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
/// use_effect(move || println!("Count changed to {count}"));
///
/// rsx! {
/// h1 { "High-Five counter: {count}" }
/// button { onclick: move |_| count += 1, "Up high!" }
/// button { onclick: move |_| count -= 1, "Down low!" }
/// }
/// }
/// ```
///
/// ## With non-reactive dependencies
/// To add non-reactive dependencies, you can use the `use_reactive` hook.
///
/// Signals will automatically be added as dependencies, so you don't need to call this method for them.
///
/// ```rust
/// # use dioxus::prelude::*;
/// # async fn sleep(delay: u32) {}
///
/// #[component]
/// fn Comp(count: u32) -> Element {
/// // Because the memo subscribes to `count` by adding it as a dependency, the memo will rerun every time `count` changes.
/// use_effect(use_reactive((&count,), |(count,)| println!("Manually manipulate the dom") ));
///
/// todo!()
/// }
/// ```
#[doc = include_str!("../docs/side_effects.md")]
#[doc = include_str!("../docs/rules_of_hooks.md")]
#[track_caller]
pub fn use_effect(callback: impl FnMut() + 'static) -> Effect {
let callback = use_callback(callback);
+13 -6
View File
@@ -5,12 +5,16 @@ use dioxus_signals::*;
use std::future::Future;
use std::ops::Deref;
/// A hook that allows you to spawn a future.
/// This future will **not** run on the server
/// The future is spawned on the next call to `wait_for_next_render` which means that it will not run on the server.
/// To run a future on the server, you should use `spawn` directly.
/// `use_future` **won't return a value**.
/// If you want to return a value from a future, use `use_resource` instead.
/// A hook that allows you to spawn a future the first time you render a component.
///
///
/// This future will **not** run on the server. To run a future on the server, you should use [`spawn_isomorphic`] directly.
///
///
/// `use_future` **won't return a value**. If you want to return a value from a future, use [`crate::use_resource()`] instead.
///
/// ## Example
///
/// ```rust
/// # use dioxus::prelude::*;
/// # use std::time::Duration;
@@ -35,6 +39,9 @@ use std::ops::Deref;
/// }
/// }
/// ```
#[doc = include_str!("../docs/rules_of_hooks.md")]
#[doc = include_str!("../docs/moving_state_around.md")]
#[doc(alias = "use_async")]
pub fn use_future<F>(mut future: impl FnMut() -> F + 'static) -> UseFuture
where
F: Future + 'static,
+2
View File
@@ -2,6 +2,8 @@ use dioxus_core::prelude::*;
use dioxus_signals::{CopyValue, Writable};
/// A hook that uses before/after lifecycle hooks to determine if the hook was run
#[doc = include_str!("../docs/rules_of_hooks.md")]
#[doc = include_str!("../docs/moving_state_around.md")]
pub fn use_hook_did_run(mut handler: impl FnMut(bool) + 'static) {
let mut did_run_ = use_hook(|| CopyValue::new(false));
+3 -35
View File
@@ -2,41 +2,9 @@ use crate::use_callback;
use dioxus_core::prelude::*;
use dioxus_signals::{Memo, Signal};
/// Creates a new Memo. The memo will be run immediately and whenever any signal it reads changes.
///
/// Memos can be used to efficiently compute derived data from signals.
///
/// ```rust
/// use dioxus::prelude::*;
/// use dioxus_signals::*;
///
/// fn App() -> Element {
/// let mut count = use_signal(|| 0);
/// let double = use_memo(move || count * 2);
/// count += 1;
/// assert_eq!(double(), count * 2);
///
/// rsx! { "{double}" }
/// }
/// ```
///
/// ## With non-reactive dependencies
/// To add non-reactive dependencies, you can use the `use_reactive` hook.
///
/// Signals will automatically be added as dependencies, so you don't need to call this method for them.
///
/// ```rust
/// # use dioxus::prelude::*;
/// # async fn sleep(delay: u32) {}
///
/// #[component]
/// fn Comp(count: u32) -> Element {
/// // Because the memo subscribes to `count` by adding it as a dependency, the memo will rerun every time `count` changes.
/// let new_count = use_memo(use_reactive((&count,), |(count,)| count + 1));
///
/// todo!()
/// }
/// ```
#[doc = include_str!("../docs/derived_state.md")]
#[doc = include_str!("../docs/rules_of_hooks.md")]
#[doc = include_str!("../docs/moving_state_around.md")]
#[track_caller]
pub fn use_memo<R: PartialEq>(f: impl FnMut() -> R + 'static) -> Memo<R> {
let callback = use_callback(f);
+18
View File
@@ -3,6 +3,14 @@ use dioxus_signals::{Readable, Writable};
use crate::use_signal;
/// A dependency is a trait that can be used to determine if a effect or selector should be re-run.
#[rustversion::attr(
since(1.78.0),
diagnostic::on_unimplemented(
message = "`Dependency` is not implemented for `{Self}`",
label = "Dependency",
note = "Dependency is automatically implemented for all tuples with less than 8 references to element that implement `PartialEq` and `Clone`. For example, `(&A, &B, &C)` implements `Dependency` automatically as long as `A`, `B`, and `C` implement `PartialEq` and `Clone`.",
)
)]
pub trait Dependency: Sized + Clone {
/// The output of the dependency
type Out: Clone + PartialEq + 'static;
@@ -20,6 +28,14 @@ impl Dependency for () {
}
/// A dependency is a trait that can be used to determine if a effect or selector should be re-run.
#[rustversion::attr(
since(1.78.0),
diagnostic::on_unimplemented(
message = "`DependencyElement` is not implemented for `{Self}`",
label = "dependency element",
note = "DependencyElement is automatically implemented for types that implement `PartialEq` and `Clone`",
)
)]
pub trait DependencyElement: 'static + PartialEq + Clone {}
impl<T> DependencyElement for T where T: 'static + PartialEq + Clone {}
@@ -83,6 +99,7 @@ impl_dep!(A = a1 a2, B = b1 b2, C = c1 c2, D = d1 d2, E = e1 e2, F = f1 f2, G =
/// println!("Data changed: {}", data);
/// }));
/// ```
#[doc = include_str!("../docs/rules_of_hooks.md")]
pub fn use_reactive<O, D: Dependency>(
non_reactive_data: D,
mut closure: impl FnMut(D::Out) -> O + 'static,
@@ -113,6 +130,7 @@ pub fn use_reactive<O, D: Dependency>(
/// println!("Data changed: {}", data);
/// }));
/// ```
#[doc = include_str!("../docs/rules_of_hooks.md")]
#[macro_export]
macro_rules! use_reactive {
(|| $($rest:tt)*) => { use_reactive( (), move |_| $($rest)* ) };
+241 -64
View File
@@ -7,66 +7,11 @@ use futures_util::{future, pin_mut, FutureExt, StreamExt};
use std::ops::Deref;
use std::{cell::Cell, future::Future, rc::Rc};
/// A memo that resolves to a value asynchronously.
/// Similar to `use_future` but `use_resource` returns a value.
/// See [`Resource`] for more details.
/// ```rust
/// # 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()).await });
///
/// rsx! {
/// // the value of the resource can be polled to
/// // conditionally render elements based off if it's future
/// // finished (Some(Ok(_)), errored Some(Err(_)),
/// // or is still running (None)
/// match &*current_weather.read() {
/// Some(Ok(weather)) => rsx! { WeatherElement { weather } },
/// Some(Err(e)) => rsx! { p { "Loading weather failed, {e}" } },
/// None => rsx! { p { "Loading..." } }
/// }
/// }
/// }
/// ```
///
/// ## With non-reactive dependencies
/// To add non-reactive dependencies, you can use the `use_reactive` hook.
///
/// Signals will automatically be added as dependencies, so you don't need to call this method for them.
///
/// ```rust
/// # use dioxus::prelude::*;
/// # async fn sleep(delay: u32) {}
///
/// #[component]
/// fn Comp(count: u32) -> Element {
/// // Because the memo subscribes to `count` by adding it as a dependency, the memo will rerun every time `count` changes.
/// let new_count = use_resource(use_reactive((&count,), |(count,)| async move {count + 1} ));
///
/// todo!()
/// }
/// ```
#[doc = include_str!("../docs/use_resource.md")]
#[doc = include_str!("../docs/rules_of_hooks.md")]
#[doc = include_str!("../docs/moving_state_around.md")]
#[doc(alias = "use_async_memo")]
#[doc(alias = "use_memo_async")]
#[must_use = "Consider using `cx.spawn` to run a future without reading its value"]
#[track_caller]
pub fn use_resource<T, F>(mut future: impl FnMut() -> F + 'static) -> Resource<T>
@@ -135,7 +80,32 @@ where
}
}
#[allow(unused)]
/// A handle to a reactive future spawned with [`use_resource`] that can be used to modify or read the result of the future.
///
/// ## Example
///
/// Reading the result of a resource:
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// # use std::time::Duration;
/// fn App() -> Element {
/// let mut revision = use_signal(|| "1d03b42");
/// let mut resource = use_resource(move || async move {
/// // This will run every time the revision signal changes because we read the count inside the future
/// reqwest::get(format!("https://github.com/DioxusLabs/awesome-dioxus/blob/{revision}/awesome.json")).await
/// });
///
/// // Since our resource may not be ready yet, the value is an Option. Our request may also fail, so the get function returns a Result
/// // The complete type we need to match is `Option<Result<String, reqwest::Error>>`
/// // We can use `read_unchecked` to keep our matching code in one statement while avoiding a temporary variable error (this is still completely safe because dioxus checks the borrows at runtime)
/// match &*resource.read_unchecked() {
/// Some(Ok(value)) => rsx! { "{value:?}" },
/// Some(Err(err)) => rsx! { "Error: {err}" },
/// None => rsx! { "Loading..." },
/// }
/// }
/// ```
#[derive(Debug)]
pub struct Resource<T: 'static> {
value: Signal<Option<T>>,
task: Signal<Task>,
@@ -143,6 +113,15 @@ pub struct Resource<T: 'static> {
callback: UseCallback<Task>,
}
impl<T> PartialEq for Resource<T> {
fn eq(&self, other: &Self) -> bool {
self.value == other.value
&& self.state == other.state
&& self.task == other.task
&& self.callback == other.callback
}
}
impl<T> Clone for Resource<T> {
fn clone(&self) -> Self {
*self
@@ -172,6 +151,28 @@ impl<T> Resource<T> {
///
/// Will not cancel the previous future, but will ignore any values that it
/// generates.
///
/// ## Example
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// # use std::time::Duration;
/// fn App() -> Element {
/// let mut revision = use_signal(|| "1d03b42");
/// let mut resource = use_resource(move || async move {
/// // This will run every time the revision signal changes because we read the count inside the future
/// reqwest::get(format!("https://github.com/DioxusLabs/awesome-dioxus/blob/{revision}/awesome.json")).await
/// });
///
/// rsx! {
/// button {
/// // We can get a signal with the value of the resource with the `value` method
/// onclick: move |_| resource.restart(),
/// "Restart resource"
/// }
/// "{resource:?}"
/// }
/// }
/// ```
pub fn restart(&mut self) {
self.task.write().cancel();
let new_task = self.callback.call();
@@ -179,18 +180,93 @@ impl<T> Resource<T> {
}
/// Forcefully cancel the resource's future.
///
/// ## Example
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// # use std::time::Duration;
/// fn App() -> Element {
/// let mut revision = use_signal(|| "1d03b42");
/// let mut resource = use_resource(move || async move {
/// reqwest::get(format!("https://github.com/DioxusLabs/awesome-dioxus/blob/{revision}/awesome.json")).await
/// });
///
/// rsx! {
/// button {
/// // We can cancel the resource before it finishes with the `cancel` method
/// onclick: move |_| resource.cancel(),
/// "Cancel resource"
/// }
/// "{resource:?}"
/// }
/// }
/// ```
pub fn cancel(&mut self) {
self.state.set(UseResourceState::Stopped);
self.task.write().cancel();
}
/// Pause the resource's future.
///
/// ## Example
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// # use std::time::Duration;
/// fn App() -> Element {
/// let mut revision = use_signal(|| "1d03b42");
/// let mut resource = use_resource(move || async move {
/// // This will run every time the revision signal changes because we read the count inside the future
/// reqwest::get(format!("https://github.com/DioxusLabs/awesome-dioxus/blob/{revision}/awesome.json")).await
/// });
///
/// rsx! {
/// button {
/// // We can pause the future with the `pause` method
/// onclick: move |_| resource.pause(),
/// "Pause"
/// }
/// button {
/// // And resume it with the `resume` method
/// onclick: move |_| resource.resume(),
/// "Resume"
/// }
/// "{resource:?}"
/// }
/// }
/// ```
pub fn pause(&mut self) {
self.state.set(UseResourceState::Paused);
self.task.write().pause();
}
/// Resume the resource's future.
///
/// ## Example
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// # use std::time::Duration;
/// fn App() -> Element {
/// let mut revision = use_signal(|| "1d03b42");
/// let mut resource = use_resource(move || async move {
/// // This will run every time the revision signal changes because we read the count inside the future
/// reqwest::get(format!("https://github.com/DioxusLabs/awesome-dioxus/blob/{revision}/awesome.json")).await
/// });
///
/// rsx! {
/// button {
/// // We can pause the future with the `pause` method
/// onclick: move |_| resource.pause(),
/// "Pause"
/// }
/// button {
/// // And resume it with the `resume` method
/// onclick: move |_| resource.resume(),
/// "Resume"
/// }
/// "{resource:?}"
/// }
/// }
/// ```
pub fn resume(&mut self) {
if self.finished() {
return;
@@ -200,7 +276,29 @@ impl<T> Resource<T> {
self.task.write().resume();
}
/// Clear the resource's value.
/// Clear the resource's value. This will just reset the value. It will not modify any running tasks.
///
/// ## Example
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// # use std::time::Duration;
/// fn App() -> Element {
/// let mut revision = use_signal(|| "1d03b42");
/// let mut resource = use_resource(move || async move {
/// // This will run every time the revision signal changes because we read the count inside the future
/// reqwest::get(format!("https://github.com/DioxusLabs/awesome-dioxus/blob/{revision}/awesome.json")).await
/// });
///
/// rsx! {
/// button {
/// // We clear the value without modifying any running tasks with the `clear` method
/// onclick: move |_| resource.clear(),
/// "Clear"
/// }
/// "{resource:?}"
/// }
/// }
/// ```
pub fn clear(&mut self) {
self.value.write().take();
}
@@ -214,6 +312,30 @@ impl<T> Resource<T> {
/// Is the resource's future currently finished running?
///
/// Reading this does not subscribe to the future's state
///
/// ## Example
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// # use std::time::Duration;
/// fn App() -> Element {
/// let mut revision = use_signal(|| "1d03b42");
/// let mut resource = use_resource(move || async move {
/// // This will run every time the revision signal changes because we read the count inside the future
/// reqwest::get(format!("https://github.com/DioxusLabs/awesome-dioxus/blob/{revision}/awesome.json")).await
/// });
///
/// // We can use the `finished` method to check if the future is finished
/// if resource.finished() {
/// rsx! {
/// "The resource is finished"
/// }
/// } else {
/// rsx! {
/// "The resource is still running"
/// }
/// }
/// }
/// ```
pub fn finished(&self) -> bool {
matches!(
*self.state.peek(),
@@ -221,12 +343,67 @@ impl<T> Resource<T> {
)
}
/// Get the current state of the resource's future.
/// Get the current state of the resource's future. This method returns a [`ReadOnlySignal`] which can be read to get the current state of the resource or passed to other hooks and components.
///
/// ## Example
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// # use std::time::Duration;
/// fn App() -> Element {
/// let mut revision = use_signal(|| "1d03b42");
/// let mut resource = use_resource(move || async move {
/// // This will run every time the revision signal changes because we read the count inside the future
/// reqwest::get(format!("https://github.com/DioxusLabs/awesome-dioxus/blob/{revision}/awesome.json")).await
/// });
///
/// // We can read the current state of the future with the `state` method
/// match resource.state().cloned() {
/// UseResourceState::Pending => rsx! {
/// "The resource is still pending"
/// },
/// UseResourceState::Paused => rsx! {
/// "The resource has been paused"
/// },
/// UseResourceState::Stopped => rsx! {
/// "The resource has been stopped"
/// },
/// UseResourceState::Ready => rsx! {
/// "The resource is ready!"
/// },
/// }
/// }
/// ```
pub fn state(&self) -> ReadOnlySignal<UseResourceState> {
self.state.into()
}
/// Get the current value of the resource's future.
/// Get the current value of the resource's future. This method returns a [`ReadOnlySignal`] which can be read to get the current value of the resource or passed to other hooks and components.
///
/// ## Example
///
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// # use std::time::Duration;
/// fn App() -> Element {
/// let mut revision = use_signal(|| "1d03b42");
/// let mut resource = use_resource(move || async move {
/// // This will run every time the revision signal changes because we read the count inside the future
/// reqwest::get(format!("https://github.com/DioxusLabs/awesome-dioxus/blob/{revision}/awesome.json")).await
/// });
///
/// // We can get a signal with the value of the resource with the `value` method
/// let value = resource.value();
///
/// // Since our resource may not be ready yet, the value is an Option. Our request may also fail, so the get function returns a Result
/// // The complete type we need to match is `Option<Result<String, reqwest::Error>>`
/// // We can use `read_unchecked` to keep our matching code in one statement while avoiding a temporary variable error (this is still completely safe because dioxus checks the borrows at runtime)
/// match &*value.read_unchecked() {
/// Some(Ok(value)) => rsx! { "{value:?}" },
/// Some(Err(err)) => rsx! { "Error: {err}" },
/// None => rsx! { "Loading..." },
/// }
/// }
/// ```
pub fn value(&self) -> ReadOnlySignal<Option<T>> {
self.value.into()
}
+16
View File
@@ -1,6 +1,22 @@
use dioxus_core::{prelude::provide_root_context, prelude::try_consume_context, use_hook};
/// Try to get a value from the root of the virtual dom, if it doesn't exist, create a new one with the closure provided.
///
/// This is useful for global context inside of libraries. Instead of having the user provide context in the root of their app, you can use this hook to create a context at the root automatically.
///
/// # Example
/// ```rust
/// # #[derive(Clone)]
/// # struct Logger;
/// use dioxus::prelude::*;
///
/// fn use_logger() -> Logger {
/// // We want one logger per app in the root. Instead of forcing the user to always provide a logger, we can insert a default logger if one doesn't exist.
/// use_root_context(|| Logger)
/// }
/// ```
#[doc = include_str!("../docs/rules_of_hooks.md")]
#[doc = include_str!("../docs/moving_state_around.md")]
pub fn use_root_context<T: 'static + Clone>(new: impl FnOnce() -> T) -> T {
use_hook(|| {
try_consume_context::<T>()
+5 -1
View File
@@ -5,7 +5,7 @@ use dioxus_signals::{ReadOnlySignal, SetCompare};
/// Creates a new SetCompare which efficiently tracks when a value changes to check if it is equal to a set of values.
///
/// Generally, you shouldn't need to use this hook. Instead you can use [`crate::use_memo`]. If you have many values that you need to compare to a single value, this hook will change updates from O(n) to O(1) where n is the number of values you are comparing to.
/// Generally, you shouldn't need to use this hook. Instead you can use [`crate::use_memo()`]. If you have many values that you need to compare to a single value, this hook will change updates from O(n) to O(1) where n is the number of values you are comparing to.
///
/// ```rust
/// use dioxus::prelude::*;
@@ -38,12 +38,16 @@ use dioxus_signals::{ReadOnlySignal, SetCompare};
/// }
/// }
/// ```
#[doc = include_str!("../docs/rules_of_hooks.md")]
#[doc = include_str!("../docs/moving_state_around.md")]
#[must_use]
pub fn use_set_compare<R: Eq + Hash>(f: impl FnMut() -> R + 'static) -> SetCompare<R> {
use_hook(move || SetCompare::new(f))
}
/// A hook that returns true if the value is equal to the value in the set compare.
#[doc = include_str!("../docs/rules_of_hooks.md")]
#[doc = include_str!("../docs/moving_state_around.md")]
#[must_use]
pub fn use_set_compare_equal<R: Eq + Hash>(
value: R,
+5
View File
@@ -30,6 +30,10 @@ use dioxus_signals::{Signal, SignalData, Storage, SyncStorage, UnsyncStorage};
/// }
/// }
/// ```
///
#[doc = include_str!("../docs/rules_of_hooks.md")]
#[doc = include_str!("../docs/moving_state_around.md")]
#[doc(alias = "use_state")]
#[track_caller]
#[must_use]
pub fn use_signal<T: 'static>(f: impl FnOnce() -> T) -> Signal<T, UnsyncStorage> {
@@ -68,6 +72,7 @@ pub fn use_signal<T: 'static>(f: impl FnOnce() -> T) -> Signal<T, UnsyncStorage>
/// }
/// }
/// ```
#[doc(alias = "use_rw")]
#[must_use]
#[track_caller]
pub fn use_signal_sync<T: Send + Sync + 'static>(f: impl FnOnce() -> T) -> Signal<T, SyncStorage> {