### Use WebSocket Hook Example
Source: https://github.com/jetli/yew-hooks/blob/main/README.md
Demonstrates the `use_websocket` hook for establishing and managing WebSocket connections. It includes sending messages, receiving messages, and updating a message history list. The example uses Rust and the Yew framework.
```rust
use yew::prelude::*;
use yew_hooks::prelude::*;
#[function_component(UseWebSocket)]
pub fn web_socket() -> Html {
let history = use_list(vec![]);
let ws = use_websocket("wss://echo.websocket.events/".to_string());
let onclick = {
let ws = ws.clone();
let history = history.clone();
Callback::from(move |_| {
let message = "Hello, world!".to_string();
ws.send(message.clone());
history.push(format!("[send]: {}", message));
})
};
{
let history = history.clone();
let ws = ws.clone();
use_effect_with(
ws.message,
move |message| {
if let Some(message) = &**message {
history.push(format!("[recv]: {}", message.clone()));
}
|| ()
},
);
}
html! {
{ "Message history: " }
{
for history.current().iter().map(|message| {
html! {
{ message }
}
})
}
}
}
```
--------------------------------
### Use Async Hook Example
Source: https://github.com/jetli/yew-hooks/blob/main/README.md
Demonstrates the usage of the `use_async` hook for asynchronous operations, such as fetching data from an API. It includes handling loading states, displaying fetched data, and managing errors. The example uses Rust and the Yew framework.
```rust
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use yew::prelude::*;
use yew_hooks::prelude::*;
#[function_component(UseAsync)]
pub fn async_demo() -> Html {
let state = use_async(async move { fetch_repo("jetli/yew-hooks".to_string()).await });
let onclick = {
let state = state.clone();
Callback::from(move |_| {
// You can trigger to run in callback or use_effect.
state.run();
})
};
html! {
{
if state.loading {
html! { "Loading, wait a sec..." }
} else {
html! {}
}
}
{
if let Some(repo) = &state.data {
html! {
<>
{ "Repo name: " }{ &repo.name }
{ "Repo full name: " }{ &repo.full_name }
{ "Repo description: " }{ &repo.description }
{ "Owner name: " }{ &repo.owner.login }
{ "Owner avatar: " }
>
}
} else {
html! {}
}
}
{
if let Some(error) = &state.error {
match error {
Error::DeserializeError => html! { "DeserializeError" },
Error::RequestError => html! { "RequestError" },
}
} else {
html! {}
}
}
}
}
async fn fetch_repo(repo: String) -> Result {
fetch::(format!("https://api.github.com/repos/{}", repo)).await
}
/// You can use reqwest or other crates to fetch your api.
async fn fetch(url: String) -> Result
where
T: DeserializeOwned,
{
let response = reqwest::get(url).await;
if let Ok(data) = response {
if let Ok(repo) = data.json::().await {
Ok(repo)
} else {
Err(Error::DeserializeError)
}
} else {
Err(Error::RequestError)
}
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
struct User {
id: i32,
login: String,
avatar_url: String,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
struct Repo {
id: i32,
name: String,
full_name: String,
description: String,
owner: User,
}
// You can use thiserror to define your errors.
#[derive(Clone, Debug, PartialEq)]
enum Error {
RequestError,
DeserializeError,
// etc.
}
```
--------------------------------
### Counter Hook Example
Source: https://github.com/jetli/yew-hooks/blob/main/README.md
Demonstrates the usage of the `use_counter` hook to manage a simple counter state within a Yew functional component. It includes buttons to increase and decrease the counter value.
```rust
use yew_hooks::prelude::*;
#[function_component(Counter)]
fn counter() -> Html {
let counter = use_counter(0);
let onincrease = {
let counter = counter.clone();
Callback::from(move |_| counter.increase())
};
let ondecrease = {
let counter = counter.clone();
Callback::from(move |_| counter.decrease())
};
html! {
<>
{ "Current value: " }
{ *counter }
>
}
}
```
--------------------------------
### use_counter Demo
Source: https://github.com/jetli/yew-hooks/blob/main/README.md
Demonstrates the usage of the `use_counter` hook in Yew. It shows how to initialize a counter, increment, decrement, set, and reset its value using callbacks.
```rust
use yew::prelude::*;
use yew_hooks::prelude::*;
#[function_component(Counter)]
fn counter() -> Html {
let counter = use_counter(0);
let onincrease = {
let counter = counter.clone();
Callback::from(move |_| counter.increase())
};
let ondecrease = {
let counter = counter.clone();
Callback::from(move |_| counter.decrease())
};
let onincreaseby = {
let counter = counter.clone();
Callback::from(move |_| counter.increase_by(10))
};
let ondecreaseby = {
let counter = counter.clone();
Callback::from(move |_| counter.decrease_by(10))
};
let onset = {
let counter = counter.clone();
Callback::from(move |_| counter.set(100))
};
let onreset = {
let counter = counter.clone();
Callback::from(move |_| counter.reset())
};
html! {
{ "Current value: " }
{ *counter }
}
}
```
--------------------------------
### Build in Release Mode
Source: https://github.com/jetli/yew-hooks/blob/main/examples/yew-app/README.md
Compiles the Yew project for production, outputting the build artifacts into the 'dist' folder. This is used for deploying the application.
```sh
trunk build
# Builds the project and places it into the `dist` folder.
```
--------------------------------
### Run in Debug Mode
Source: https://github.com/jetli/yew-hooks/blob/main/examples/yew-app/README.md
Builds the Yew project and serves it in a new browser tab, with automatic reloading on file changes. This command is used for development and debugging.
```sh
trunk serve
# Builds the project and opens it in a new browser tab. Auto-reloads when the project changes.
```
--------------------------------
### Run Unit Tests
Source: https://github.com/jetli/yew-hooks/blob/main/examples/yew-app/README.md
Executes the unit tests for the Yew project in a headless Chrome environment. This command is crucial for ensuring code quality and correctness.
```sh
wasm-pack test --headless --chrome
# Runs tests
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.