Skip to content

Instantly share code, notes, and snippets.

@RNGKing
Created June 28, 2023 05:25
Show Gist options
  • Save RNGKing/96edbaa3149d171a481ada63a4b5581b to your computer and use it in GitHub Desktop.
Save RNGKing/96edbaa3149d171a481ada63a4b5581b to your computer and use it in GitHub Desktop.
Something is not quite right with how I made the action works in Leptos?
[package]
name = "leptos_frontend"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
leptos = "0.3.1"
reqwasm = "0.5"
serde = { version = "1", features = ["derive"] }
thiserror = "1"
wasm-bindgen = "0.2.87"
json = "0.12.4"
use leptos::{*, ev::SubmitEvent};
use serde::{Deserialize, Serialize};
use thiserror::Error;
use wasm_bindgen::*;
#[derive(Error, Clone, Debug)]
pub enum FetchError {
#[error("Please request more than zero cats.")]
NonZeroCats,
#[error("Error loading data from serving.")]
Request,
#[error("Error deserializaing cat data from request.")]
Json,
#[error("Error while executing response")]
Response
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
struct CatInfo {
name : String,
coat: String
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
struct CatCreate{
name : String,
coat : String
}
async fn fetch_cats(_ : ()) -> Result<Vec<CatInfo>, FetchError> {
let res = reqwasm::http::Request::get(&format!(
"http://127.0.0.1:4000/cats"
))
.mode(reqwasm::http::RequestMode::Cors)
.send()
.await
.map_err(|_| FetchError::Request)?
.json::<Vec<CatInfo>>()
.await
.map_err(|_| FetchError::Json)?
.into_iter()
.map(|cat| CatInfo{name:cat.name, coat:cat.coat})
.collect::<Vec<_>>();
Ok(res)
}
async fn submit_cats(create : CatCreate) -> Result< (), FetchError> {
leptos::log!("Submitting cat request");
let json_str = format!("{{\"name\":{},\"coat\":{}}}", create.name, create.coat);
let res = reqwasm::http::Request::post(&format!(
"http://127.0.0.1:4000/cats"
))
.header("Content-Type", "application/json")
.body(JsValue::from_str(&json_str))
.mode(reqwasm::http::RequestMode::Cors)
.send()
.await;
match res {
Ok(resp) =>{
return if resp.ok() {Ok(())} else {Err(FetchError::Request)};
},
Err(_) => Err(FetchError::Response),
}
}
#[component]
fn App(cx: Scope) -> impl IntoView{
let (cat_name, set_cat_name) = create_signal(cx, "".to_string());
let (cat_fur_color, set_fur_color) = create_signal(cx, "".to_string());
let (empty, _set_empty) = create_signal(cx, ());
let cats = create_local_resource(cx, empty, fetch_cats);
let submit_action = create_action(cx, |input: &CatCreate| {
let input = input.clone();
async move {submit_cats(input)}
});
let cats_view = move || {
cats.read(cx).map(|data| {
data.map(|data| {
data.iter()
.map(|s| {
let clone = s.clone();
view!{ cx, <h1>{clone.name}</h1><h3>{clone.coat}</h3>}
})
.collect_view(cx)
})
})
};
let on_submit_value = submit_action.value();
let on_submit_input = submit_action.input();
let on_submit = move |ev: SubmitEvent| {
ev.prevent_default();
let create = CatCreate{name:cat_name.get(), coat: cat_fur_color.get()};
leptos::log!("{}, {}", create.name, create.coat);
submit_action.dispatch(create);
leptos::log!("Executing code");
};
view!{
cx,
<h1>"The Cat App"</h1>
<div>
<form on:submit=on_submit>
<label>
"Cat Name"
<input type="text" name="name" placeholder="Cat Name" on:input= move |ev| {set_cat_name(event_target_value(&ev))}/>
</label>
<label>
"Coat Color"
<input type="text" name="name" placeholder="Cat Fur Color" on:input= move |ev| {set_fur_color(event_target_value(&ev))}/>
</label>
<input type="submit" value="Submit"/>
</form>
</div>
<div>
<Transition fallback = move || {
view!{cx, <div>"Loading..."</div>}
}>
{cats_view}
</Transition>
</div>
}
}
fn main() {
mount_to_body(|cx| view!{ cx, <App/>})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment