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

@@ -0,0 +1,133 @@
## Compiler errors you may run into while using event handlers
<details>
<summary>function requires argument type to outlive `'static`</summary>
Event handler in Dioxus need only access data that can last for the entire lifetime of the application. That generally means data that is moved into the closure. **If you get this error, you may have forgotten to add `move` to your closure.**
Broken component:
```rust, compile_fail
# use dioxus::prelude::*;
// We return an Element which can last as long as the component is on the screen
fn App() -> Element {
// Signals are `Copy` which makes them very easy to move into `'static` closures like event handlers
let state = use_signal(|| "hello world".to_string());
rsx! {
button {
// ❌ Without `move`, rust will try to borrow the `state` signal which fails because the state signal is dropped at the end of the function
onclick: |_| {
println!("You clicked the button! The state is: {state}");
},
"Click me"
}
}
// The state signal is dropped here, but the event handler still needs to access it
}
```
Fixed component:
```rust, no_run
# use dioxus::prelude::*;
fn App() -> Element {
let state = use_signal(|| "hello world".to_string());
rsx! {
button {
// ✅ The `move` keyword tells rust it can move the `state` signal into the closure. Since the closure owns the signal state, it can read it even after the function returns
onclick: move |_| {
println!("You clicked the button! The state is: {state}");
},
"Click me"
}
}
}
```
</details>
<details>
<summary>use of moved value: `your_value` value used here after move</summary>
Data in rust has a single owner. If you run into this error, you have likely tried to move data that isn't `Copy` into two different closures. **You can fix this issue by making your data `Copy` or calling `clone` on it before you move it into the closure.**
Broken component:
```rust, compile_fail
# use dioxus::prelude::*;
// `MyComponent` accepts a string which cannot be copied implicitly
#[component]
fn MyComponent(string: String) -> Element {
rsx! {
button {
// ❌ We are moving the string into the onclick handler which means we can't access it elsewhere
onclick: move |_| {
println!("{string}");
},
"Print hello world"
}
button {
// ❌ Since we already moved the string, we can't move it into the onclick handler again. This will cause a compiler error
onclick: move |_| {
println!("{string}");
},
"Print hello world again"
}
}
}
```
You can fix this issue by either:
- Making your data `Copy` with `ReadOnlySignal`:
```rust, no_run
# use dioxus::prelude::*;
// `MyComponent` accepts `ReadOnlySignal<String>` which implements `Copy`
#[component]
fn MyComponent(string: ReadOnlySignal<String>) -> Element {
rsx! {
button {
// ✅ Because the `string` signal is `Copy`, we can copy it into the closure while still having access to it elsewhere
onclick: move |_| println!("{}", string),
"Print hello world"
}
button {
// ✅ Since `string` is `Copy`, we can move it into the onclick handler again
onclick: move |_| println!("{}", string),
"Print hello world again"
}
}
}
```
- Calling `clone` on your data before you move it into the closure:
```rust, no_run
# use dioxus::prelude::*;
// `MyComponent` accepts a string which doesn't implement `Copy`
#[component]
fn MyComponent(string: String) -> Element {
rsx! {
button {
// ✅ The string only has one owner. We could move it into this closure, but since we want to use the string in other closures later, we will clone it instead
onclick: {
// Clone the string in a new block
let string = string.clone();
// Then move the cloned string into the closure
move |_| println!("{}", string)
},
"Print hello world"
}
button {
// ✅ We don't use the string after this closure, so we can just move it into the closure directly
onclick: move |_| println!("{}", string),
"Print hello world again"
}
}
}
```
</details>
+125
View File
@@ -0,0 +1,125 @@
# Communicating with JavaScript
You can use the `eval` function to execute JavaScript code in your application with the desktop, mobile, web or liveview renderers. Eval takes a block of JavaScript code (that may be asynchronous) and returns a `UseEval` object that you can use to send data to the JavaScript code and receive data from it.
<div class="warning">
## Safety
Please be careful when executing JavaScript code with `eval`. You should only execute code that you trust. **This applies especially to web targets, where the JavaScript context has access to most, if not all of your application data.** Running untrusted code can lead to a [cross-site scripting](https://developer.mozilla.org/en-US/docs/Glossary/Cross-site_scripting) (XSS) vulnerability.
</div>
```rust
use dioxus::prelude::*;
fn App() -> Element {
rsx! {
button {
onclick: move |_| async move {
// Eval is a global function you can use anywhere inside Dioxus. It will execute the given JavaScript code.
let result = eval(r#"console.log("Hello World");
return "Hello World";"#);
// You can use the `await` keyword to wait for the result of the JavaScript code.
println!("{:?}", result.await);
},
"Log Hello World"
}
}
}
```
## Sending data to JavaScript
When you execute JavaScript code with `eval`, you can pass data to it by formatting the value into the JavaScript code or sending values to the `UseEval` channel.
```rust
use dioxus::prelude::*;
fn app() -> Element {
rsx! {
button {
onclick: move |_| {
// You can pass initial data to the eval function by formatting it into the JavaScript code.
const LOOP_COUNT: usize = 10;
let eval = eval(&format!(r#"for(let i = 0; i < {LOOP_COUNT}; i++) {{
// You can receive values asynchronously with the the `await dioxus.recv()` method.
let value = await dioxus.recv();
console.log("Received", value);
}}"#));
// You can send values from rust to the JavaScript code with the `send` method on the object returned by `eval`.
for i in 0..LOOP_COUNT {
eval.send(i.into()).unwrap();
}
},
"Log Count"
}
}
}
```
## Sending data from JavaScript
The `UseEval` struct also contains methods for receiving values you send from JavaScript. You can use the `dioxus.send()` method to send values to the JavaScript code and the `UseEval::recv()` method to receive values from the JavaScript code.
```rust
use dioxus::prelude::*;
fn app() -> Element {
rsx! {
button {
onclick: move |_| async move {
// You can send values from rust to the JavaScript code by using the `send` method on the object returned by `eval`.
let mut eval = eval(r#"for(let i = 0; i < 10; i++) {
// You can send values asynchronously with the `dioxus.send()` method.
dioxus.send(i);
}"#);
// You can receive values from the JavaScript code with the `recv` method on the object returned by `eval`.
for _ in 0..10 {
let value = eval.recv().await.unwrap();
println!("Received {}", value);
}
},
"Log Count"
}
}
}
```
## Interacting with the DOM with Eval
You can also use the `eval` function to execute JavaScript code that reads or modifies the DOM. If you want to interact with the mounted DOM, you need to use `eval` inside the [`dioxus_hooks::use_effect`] hook which runs after the component has been mounted.
```rust
use dioxus::prelude::*;
const SCRIPT: &str = r#"
let element = document.getElementById("my-element");
element.innerHTML = "Hello World";
return element.getAttribute("data-count");
"#;
fn app() -> Element {
// ❌ You shouldn't run eval in the body of a component. This will run before the component has been mounted
// eval(SCRIPT);
// ✅ You should run eval inside an effect or event. This will run after the component has been mounted
use_effect(move || {
spawn(async {
let count = eval(SCRIPT).await;
println!("Count is {:?}", count);
});
});
rsx! {
div {
id: "my-element",
"data-count": "123",
}
}
}
```
+86
View File
@@ -0,0 +1,86 @@
# Event Handlers
Event Handlers let you react to user input in your application. In Dioxus, event handlers accept a closure that is called when the event occurs:
```rust, no_run
use dioxus::prelude::*;
fn App() -> Element {
rsx! {
button {
// The `onclick` event accepts a closure with the signature `fn(Event)`
onclick: |event_data| println!("clicked! I got the event data: {event_data:?}"),
"Click me"
}
}
}
```
## Event Lifetimes
Events take a closure with the `'static` lifetime. This means that the closure can only access data that either exists for the entire lifetime of the application, or data that you move into the closure.
State in dioxus is `copy` which makes it very easy to move into `'static` closures like event handlers:
```rust, no_run
# use dioxus::prelude::*;
let mut count = use_signal(|| 0);
rsx! {
button {
// Since we added the `move` keyword, the closure will move the `count` signal into the closure
onclick: move |_| {
// This will panic because the `count` signal is not in scope
count.set(count() + 1);
},
"Click me"
}
};
```
If you need to access data that is not `Copy`, you may need to clone the data before you move it into the closure:
```rust, no_run
# use dioxus::prelude::*;
// String is not `Copy`
let string = "hello world".to_string();
rsx! {
button {
// The string only has one owner. We could move it into this closure, but since we want to use the string in other closures later, we will clone it instead
onclick: {
// Clone the string in a new block
let string = string.clone();
// Then move the cloned string into the closure
move |_| println!("{}", string)
},
"Print hello world"
}
button {
// We don't use the string after this closure, so we can just move it into the closure directly
onclick: move |_| println!("{}", string),
"Print hello world again"
}
};
```
## Async Event Handlers
In addition to closures that return nothing, you can also use async closures to handle events. If you return an async block from an event handler, dioxus will automatically spawn it:
```rust, no_run
use dioxus::prelude::*;
fn App() -> Element {
rsx! {
button {
// The `onclick` event can also accept a closure that returns an async block
onclick: move |_| async move {
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
println!("You clicked the button one second ago!");
},
"Click me"
}
}
}
```