Internationalization: move guide to en folder and preserve its history. (#494)

* chore: move guide to en folder

* docs: add english as language
This commit is contained in:
Jon Kelley authored and GitHub committed 2022-07-09 12:31:46 -04:00
1 parent 7fdc72726d
commit c97ca7dff6
69 files changed
+4 -1

No files matched your search

@@ -0,0 +1,33 @@
# Antipatterns
This example shows what not to do and provides a reason why a given pattern is considered an "AntiPattern". Most anti-patterns are considered wrong due performance reasons, or for harming code re-usability.
## Unnecessarily Nested Fragments
Fragments don't mount a physical element to the DOM immediately, so Dioxus must recurse into its children to find a physical DOM node. This process is called "normalization". This means that deeply nested fragments make Dioxus perform unnecessary work. Prefer one or two levels of fragments / nested components until presenting a true DOM element.
Only Component and Fragment nodes are susceptible to this issue. Dioxus mitigates this with components by providing an API for registering shared state without the Context Provider pattern.
```rust
{{#include ../../examples/anti_patterns.rs:nested_fragments}}
```
## Incorrect Iterator Keys
As described in the conditional rendering chapter, list items must have unique keys that are associated with the same items across renders. This helps Dioxus associate state with the contained components, and ensures good diffing performance. Do not omit keys, unless you know that the list is static and will never change.
```rust
{{#include ../../examples/anti_patterns.rs:iter_keys}}
```
## Avoid Interior Mutability in Props
While it is technically acceptable to have a `Mutex` or a `RwLock` in the props, they will be difficult to use.
Suppose you have a struct `User` containing the field `username: String`. If you pass a `Mutex<User>` prop to a `UserComponent` component, that component may wish to pass the username as a `&str` prop to a child component. However, it cannot pass that borrowed field down, since it only would live as long as the `Mutex`'s lock, which belongs to the `UserComponent` function. Therefore, the component will be forced to clone the `username` field.
## Avoid Updating State During Render
Every time you update the state, Dioxus needs to re-render the component – this is inefficient! Consider refactoring your code to avoid this.
Also, if you unconditionally update the state during render, it will be re-rendered in an infinite loop.
@@ -0,0 +1,158 @@
# Error handling
A selling point of Rust for web development is the reliability of always knowing where errors can occur and being forced to handle them
However, we haven't talked about error handling at all in this guide! In this chapter, we'll cover some strategies in handling errors to ensure your app never crashes.
## The simplest – returning None
Astute observers might have noticed that `Element` is actually a type alias for `Option<VNode>`. You don't need to know what a `VNode` is, but it's important to recognize that we could actually return nothing at all:
```rust
fn App(cx: Scope) -> Element {
None
}
```
This lets us add in some syntactic sugar for operations we think *shouldn't* fail, but we're still not confident enough to "unwrap" on.
> The nature of `Option<VNode>` might change in the future as the `try` trait gets upgraded.
```rust
fn App(cx: Scope) -> Element {
// immediately return "None"
let name = cx.use_hook(|_| Some("hi"))?;
}
```
## Early return on result
Because Rust can't accept both Options and Results with the existing try infrastructure, you'll need to manually handle Results. This can be done by converting them into Options or by explicitly handling them.
```rust
fn App(cx: Scope) -> Element {
// Convert Result to Option
let name = cx.use_hook(|_| "1.234").parse().ok()?;
// Early return
let count = cx.use_hook(|_| "1.234");
let val = match count.parse() {
Ok(val) => val
Err(err) => return cx.render(rsx!{ "Parsing failed" })
};
}
```
Notice that while hooks in Dioxus do not like being called in conditionals or loops, they *are* okay with early returns. Returning an error state early is a completely valid way of handling errors.
## Match results
The next "best" way of handling errors in Dioxus is to match on the error locally. This is the most robust way of handling errors, though it doesn't scale to architectures beyond a single component.
To do this, we simply have an error state built into our component:
```rust
let err = use_state(&cx, || None);
```
Whenever we perform an action that generates an error, we'll set that error state. We can then match on the error in a number of ways (early return, return Element, etc).
```rust
fn Commandline(cx: Scope) -> Element {
let error = use_state(&cx, || None);
cx.render(match *error {
Some(error) => rsx!(
h1 { "An error occured" }
)
None => rsx!(
input {
oninput: move |_| error.set(Some("bad thing happened!")),
}
)
})
}
```
## Passing error states through components
If you're dealing with a handful of components with minimal nesting, you can just pass the error handle into child components.
```rust
fn Commandline(cx: Scope) -> Element {
let error = use_state(&cx, || None);
if let Some(error) = **error {
return cx.render(rsx!{ "An error occured" });
}
cx.render(rsx!{
Child { error: error.clone() }
Child { error: error.clone() }
Child { error: error.clone() }
Child { error: error.clone() }
})
}
```
Much like before, our child components can manually set the error during their own actions. The advantage to this pattern is that we can easily isolate error states to a few components at a time, making our app more predictable and robust.
## Going global
A strategy for handling cascaded errors in larger apps is through signaling an error using global state. This particular pattern involves creating an "error" context, and then setting it wherever relevant. This particular method is not as "sophisticated" as React's error boundary, but it is more fitting for Rust.
To get started, consider using a built-in hook like `use_context` and `use_context_provider` or Fermi. Of course, it's pretty easy to roll your own hook too.
At the "top" of our architecture, we're going to want to explicitly declare a value that could be an error.
```rust
enum InputError {
None,
TooLong,
TooShort,
}
static INPUT_ERROR: Atom<InputError> = |_| InputError::None;
```
Then, in our top level component, we want to explicitly handle the possible error state for this part of the tree.
```rust
fn TopLevel(cx: Scope) -> Element {
let error = use_read(&cx, INPUT_ERROR);
match error {
TooLong => return cx.render(rsx!{ "FAILED: Too long!" }),
TooShort => return cx.render(rsx!{ "FAILED: Too Short!" }),
_ => {}
}
}
```
Now, whenever a downstream component has an error in its actions, it can simply just set its own error state:
```rust
fn Commandline(cx: Scope) -> Element {
let set_error = use_set(&cx, INPUT_ERROR);
cx.render(rsx!{
input {
oninput: move |evt| {
if evt.value.len() > 20 {
set_error(InputError::TooLong);
}
}
}
})
}
```
This approach to error handling is best in apps that have "well defined" error states. Consider using a crate like `thiserror` or `anyhow` to simplify the generation of the error types.
This pattern is widely popular in many contexts and is particularly helpful whenever your code generates a non-recoverable error. You can gracefully capture these "global" error states without panicking or mucking up state.
+29
View File
@@ -0,0 +1,29 @@
# Best Practices
## Reusable Components
As much as possible, break your code down into small, reusable components and hooks, instead of implementing large chunks of the UI in a single component. This will help you keep the code maintainable – it is much easier to e.g. add, remove or re-order parts of the UI if it is organized in components.
Organize your components in modules to keep the codebase easy to navigate!
## Minimize State Dependencies
While it is possible to share state between components, this should only be done when necessary. Any component that is associated with a particular state object needs to be re-rendered when that state changes. For this reason:
- Keep state local to a component if possible
- When sharing state through props, only pass down the specific data necessary
## Reusable Libraries
When publishing a library designed to work with Dioxus, we highly advise using only the core feature on the `dioxus` crate. This makes your crate compile faster, makes it more stable, and avoids bringing in incompatible libraries that might make it not compile on unsupported platforms.
❌ Don't include unnecessary dependencies in libraries:
```toml
dioxus = { version = "...", features = ["web", "desktop", "full"]}
```
✅ Only add the features you need:
```toml
dioxus = { version = "...", features = "core"}
```