merge new suspense

This commit is contained in:
Evan Almloff committed 2023-07-17 09:56:38 -07:00
commit 913d1f0491
40 files changed
+361 -656

No files matched your search

+2
View File
@@ -21,10 +21,12 @@
- [Hooks & Component State](interactivity/hooks.md)
- [User Input](interactivity/user_input.md)
- [Sharing State](interactivity/sharing_state.md)
- [Memoization](interactivity/memoization.md)
- [Custom Hooks](interactivity/custom_hooks.md)
- [Dynamic Rendering](interactivity/dynamic_rendering.md)
- [Routing](interactivity/router.md)
- [Async](async/index.md)
- [UseEffect](async/use_effect.md)
- [UseFuture](async/use_future.md)
- [UseCoroutine](async/use_coroutine.md)
- [Spawning Futures](async/spawn.md)
@@ -94,8 +94,10 @@ Calling `deref` or `deref_mut` is actually more complex than it seems. When a va
Sometimes you want a signal to propagate across your app, either through far-away siblings or through deeply-nested components. In these cases, we use Dirac: Dioxus's first-class state management toolkit. Dirac atoms automatically implement the Signal API. This component will bind the input element to the `TITLE` atom.
```rust, no_run
const TITLE: Atom<String> = || "".to_string();
const TITLE: Atom<String> = Atom(|| "".to_string());
const Provider: Component = |cx|{
let title = use_signal(cx, &TITLE);
render!(input { value: title })
@@ -131,7 +133,8 @@ By default, Dioxus is limited when you use iter/map. With the `For` component, y
Dioxus automatically understands how to use your signals when mixed with iterators through `Deref`/`DerefMut`. This lets you efficiently map collections while avoiding the re-rendering of lists. In essence, signals act as a hint to Dioxus on how to avoid un-necessary checks and renders, making your app faster.
```rust, no_run
const DICT: AtomFamily<String, String> = |_| {};
const DICT: AtomFamily<String, String> = AtomFamily(|_| {});
const List: Component = |cx|{
let dict = use_signal(cx, &DICT);
cx.render(rsx!(
@@ -142,14 +145,6 @@ const List: Component = |cx|{
};
```
## Remote Signals
Apps that use signals will enjoy a pleasant hybrid of server-side and client-side rendering.
```rust, no_run
```
## How does it work?
Signals internally use Dioxus' asynchronous rendering infrastructure to perform updates out of the tree.
+4 -4
View File
@@ -143,7 +143,7 @@ async fn editor_service(rx: UnboundedReceiver<EditorCommand>) {
We can combine coroutines with [Fermi](https://docs.rs/fermi/latest/fermi/index.html) to emulate Redux Toolkit's Thunk system with much less headache. This lets us store all of our app's state _within_ a task and then simply update the "view" values stored in Atoms. It cannot be understated how powerful this technique is: we get all the perks of native Rust tasks with the optimizations and ergonomics of global state. This means your _actual_ state does not need to be tied up in a system like Fermi or Redux – the only Atoms that need to exist are those that are used to drive the display/UI.
```rust, no_run
static USERNAME: Atom<String> = |_| "default".to_string();
static USERNAME: Atom<String> = Atom(|_| "default".to_string());
fn app(cx: Scope) -> Element {
let atoms = use_atom_root(cx);
@@ -156,7 +156,7 @@ fn app(cx: Scope) -> Element {
}
fn Banner(cx: Scope) -> Element {
let username = use_read(cx, USERNAME);
let username = use_read(cx, &USERNAME);
cx.render(rsx!{
h1 { "Welcome back, {username}" }
@@ -174,8 +174,8 @@ enum SyncAction {
}
async fn sync_service(mut rx: UnboundedReceiver<SyncAction>, atoms: AtomRoot) {
let username = atoms.write(USERNAME);
let errors = atoms.write(ERRORS);
let username = atoms.write(&USERNAME);
let errors = atoms.write(&ERRORS);
while let Ok(msg) = rx.next().await {
match msg {
+41
View File
@@ -0,0 +1,41 @@
# UseEffect
[`use_effect`](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_effect.html) lets you run a callback that returns a future, which will be re-run when its [dependencies](#dependencies) change. This is useful to syncrhonize with external events.
## Dependencies
You can make the callback re-run when some value changes. For example, you might want to fetch a user's data only when the user id changes. You can provide a tuple of "dependencies" to the hook. It will automatically re-run it when any of those dependencies change.
## Example
```rust, no_run
#[inline_props]
fn Profile(cx: Scope, id: usize) -> Element {
let name = use_state(cx, || None);
// Only fetch the user data when the id changes.
use_effect(cx, (id,), |(id,)| {
to_owned![name];
async move {
let user = fetch_user(id).await;
name.set(user.name);
}
});
// Because the dependencies are empty, this will only run once.
// An empty tuple is always equal to an empty tuple.
use_effect(cx, (), |()| async move {
println!("Hello, World!");
});
let name = name.get().clone().unwrap_or("Loading...".to_string());
render!(
p { "{name}" }
)
}
fn app(cx: Scope) -> Element {
render!(Profile { id: 0 })
}
```
@@ -113,14 +113,14 @@ enum InputError {
TooShort,
}
static INPUT_ERROR: Atom<InputError> = |_| InputError::None;
static INPUT_ERROR: Atom<InputError> = Atom(|_| InputError::None);
```
Then, in our top level component, we want to explicitly handle the possible error state for this part of the tree.
```rust, no_run
fn TopLevel(cx: Scope) -> Element {
let error = use_read(cx, INPUT_ERROR);
let error = use_read(cx, &INPUT_ERROR);
match error {
TooLong => return cx.render(rsx!{ "FAILED: Too long!" }),
@@ -134,7 +134,7 @@ Now, whenever a downstream component has an error in its actions, it can simply
```rust, no_run
fn Commandline(cx: Scope) -> Element {
let set_error = use_set(cx, INPUT_ERROR);
let set_error = use_set(cx, &INPUT_ERROR);
cx.render(rsx!{
input {
@@ -0,0 +1,19 @@
# Memoization
[`use_memo`](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_memo.html) let's you memorize values and thus save computation time. This is useful for expensive calculations.
```rust, no_run
#[inline_props]
fn Calculator(cx: Scope, number: usize) -> Element {
let bigger_number = use_memo(cx, (number,), |(number,)| {
// This will only be calculated when `number` has changed.
number * 100
});
render!(
p { "{bigger_number}" }
)
}
fn app(cx: Scope) -> Element {
render!(Calculator { number: 0 })
}
```
@@ -32,7 +32,7 @@ Finally, a third component will render the other two as children. It will be res
![Meme Editor Screenshot: An old plastic skeleton sitting on a park bench. Caption: "me waiting for a language feature"](./images/meme_editor_screenshot.png)
## Using Context
## Using Shared State
Sometimes, some state needs to be shared between multiple components far down the tree, and passing it down through props is very inconvenient.
@@ -42,7 +42,7 @@ Suppose now that we want to implement a dark mode toggle for our app. To achieve
Now, we could write another `use_state` in the top component, and pass `is_dark_mode` down to every component through props. But think about what will happen as the app grows in complexity – almost every component that renders any CSS is going to need to know if dark mode is enabled or not – so they'll all need the same dark mode prop. And every parent component will need to pass it down to them. Imagine how messy and verbose that would get, especially if we had components several levels deep!
Dioxus offers a better solution than this "prop drilling" – providing context. The [`use_context_provider`](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_context_provider.html) hook is similar to `use_ref`, but it makes it available through [`use_context`](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_context.html) for all children components.
Dioxus offers a better solution than this "prop drilling" – providing context. The [`use_shared_state_provider`](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_shared_state_provider.html) hook is similar to `use_ref`, but it makes it available through [`use_shared_state`](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_shared_state.html) for all children components.
First, we have to create a struct for our dark mode configuration:
@@ -62,7 +62,7 @@ As a result, any child component of `App` (direct or not), can access the `DarkM
{{#include ../../../examples/meme_editor_dark_mode.rs:use_context}}
```
> `use_context` returns `Option<UseSharedState<DarkMode>>` here. If the context has been provided, the value is `Some(UseSharedState<DarkMode>)`, which you can call `.read` or `.write` on, similarly to `UseRef`. Otherwise, the value is `None`.
> `use_shared_state` returns `Option<UseSharedState<DarkMode>>` here. If the context has been provided, the value is `Some(UseSharedState<DarkMode>)`, which you can call `.read` or `.write` on, similarly to `UseRef`. Otherwise, the value is `None`.
For example, here's how we would implement the dark mode toggle, which both reads the context (to determine what color it should render) and writes to it (to toggle dark mode):
+4 -4
View File
@@ -105,7 +105,7 @@ async fn editor_service(rx: UnboundedReceiver<EditorCommand>) {
Podemos combinar corrotinas com `Fermi` para emular o sistema `Thunk` do **Redux Toolkit** com muito menos dor de cabeça. Isso nos permite armazenar todo o estado do nosso aplicativo _dentro_ de uma tarefa e, em seguida, simplesmente atualizar os valores de "visualização" armazenados em `Atoms`. Não pode ser subestimado o quão poderosa é essa técnica: temos todas as vantagens das tarefas nativas do Rust com as otimizações e ergonomia do estado global. Isso significa que seu estado _real_ não precisa estar vinculado a um sistema como `Fermi` ou `Redux` – os únicos `Atoms` que precisam existir são aqueles que são usados para controlar a interface.
```rust, no_run
static USERNAME: Atom<String> = |_| "default".to_string();
static USERNAME: Atom<String> = Atom(|_| "default".to_string());
fn app(cx: Scope) -> Element {
let atoms = use_atom_root(cx);
@@ -118,7 +118,7 @@ fn app(cx: Scope) -> Element {
}
fn Banner(cx: Scope) -> Element {
let username = use_read(cx, USERNAME);
let username = use_read(cx, &USERNAME);
cx.render(rsx!{
h1 { "Welcome back, {username}" }
@@ -134,8 +134,8 @@ enum SyncAction {
}
async fn sync_service(mut rx: UnboundedReceiver<SyncAction>, atoms: AtomRoot) {
let username = atoms.write(USERNAME);
let errors = atoms.write(ERRORS);
let username = atoms.write(&USERNAME);
let errors = atoms.write(&ERRORS);
while let Ok(msg) = rx.next().await {
match msg {
@@ -113,14 +113,14 @@ enum InputError {
TooShort,
}
static INPUT_ERROR: Atom<InputError> = |_| InputError::None;
static INPUT_ERROR: Atom<InputError> = Atom(|_| InputError::None);
```
Então, em nosso componente de nível superior, queremos tratar explicitamente o possível estado de erro para esta parte da árvore.
```rust, no_run
fn TopLevel(cx: Scope) -> Element {
let error = use_read(cx, INPUT_ERROR);
let error = use_read(cx, &INPUT_ERROR);
match error {
TooLong => return cx.render(rsx!{ "FAILED: Too long!" }),
@@ -134,7 +134,7 @@ Agora, sempre que um componente _downstream_ tiver um erro em suas ações, ele
```rust, no_run
fn Commandline(cx: Scope) -> Element {
let set_error = use_set(cx, INPUT_ERROR);
let set_error = use_set(cx, &INPUT_ERROR);
cx.render(rsx!{
input {