allow returning values from use_eval

This commit is contained in:
Evan Almloff committed 2022-12-08 10:44:56 -06:00
1 parent 1e99e35572
commit e863ef29b8
6 files changed
+100 -13

No files matched your search

+20 -4
View File
@@ -1,6 +1,10 @@
//! Utilities specific to websys
use std::str::FromStr;
use dioxus_core::*;
use serde::de::Error;
use serde_json::Value;
/// Get a closure that executes any JavaScript in the webpage.
///
@@ -15,12 +19,24 @@ use dioxus_core::*;
///
/// The closure will panic if the provided script is not valid JavaScript code
/// or if it returns an uncaught error.
pub fn use_eval<S: std::string::ToString>(cx: &ScopeState) -> &dyn Fn(S) {
pub fn use_eval<S: std::string::ToString>(
cx: &ScopeState,
) -> &dyn Fn(S) -> Result<Value, serde_json::Error> {
cx.use_hook(|| {
|script: S| {
js_sys::Function::new_no_args(&script.to_string())
.call0(&wasm_bindgen::JsValue::NULL)
.expect("failed to eval script");
let body = script.to_string();
if let Ok(value) =
js_sys::Function::new_no_args(&body).call0(&wasm_bindgen::JsValue::NULL)
{
if let Ok(stringified) = js_sys::JSON::stringify(&value) {
let string: String = stringified.into();
Value::from_str(&string)
} else {
Err(serde_json::Error::custom("Failed to stringify result"))
}
} else {
Err(serde_json::Error::custom("Failed to execute script"))
}
}
})
}