Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use_server_future is not properly reactive #1950

Closed
Nnamdi-sys opened this issue Feb 17, 2024 · 1 comment · Fixed by #2033
Closed

use_server_future is not properly reactive #1950

Nnamdi-sys opened this issue Feb 17, 2024 · 1 comment · Fixed by #2033
Assignees
Labels
bug Something isn't working fullstack related to the fullstack crate web relating to the web renderer for dioxus

Comments

@Nnamdi-sys
Copy link

Problem

I'm struggling with re-rendering HTML using the dangerous_inner_html attribute.

The HTML String is being generated from a server function and called with use_server_future.

On the first launch the HTML renders correctly, but after that the HTML doesn't get rendered.

I have checked the console logs and I can see the HTML string is generated correctly.

Expected behavior

HTML Should be re-rendered on submit of the form.

Environment:

  • Dioxus version: 0.4.3
  • Rust version: 1.72.0
  • OS info: MacOS
  • App platform: fullstack

main.rs

#![allow(non_snake_case, unused)]

use dioxus::html::{button, input, label};
use dioxus::prelude::*;
use dioxus_fullstack::prelude::*;
use serde::{Deserialize, Serialize};

#[cfg(feature = "ssr")]
use finalytics::charts::portfolio::PortfolioCharts;
#[cfg(feature = "ssr")]
use finalytics::data::ticker::Interval;
#[cfg(feature = "ssr")]
use finalytics::analytics::optimization::ObjectiveFunction;
use log::log;


fn main() {
   #[cfg(feature = "web")]
   dioxus_web::launch_cfg(app, dioxus_web::Config::new().hydrate(true));
   #[cfg(feature = "web")]
   wasm_logger::init(wasm_logger::Config::default());
   #[cfg(feature = "ssr")]
   {
       tokio::runtime::Runtime::new()
           .unwrap()
           .block_on(async move {
               let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 8080));
               axum::Server::bind(&addr)
                   .serve(
                       axum::Router::new()
                           .serve_dioxus_application("", ServeConfigBuilder::new(app, ()))
                           .into_make_service(),
                   )
                   .await
                   .unwrap();
           });
   }
}

fn app(cx: Scope) -> Element {
   cx.render(rsx! {
       h1 { "Finalytics" }
       div {
           PortfolioComponent {}
       }
   })
}


#[component]
pub fn PortfolioComponent(cx: Scope) -> Element {
   let symbols = use_state(cx, || "AAPL,MSFT,NVDA,BTC-USD".to_string());
   let benchmark_symbol = use_state(cx, || "^GSPC".to_string());
   let start_date = use_state(cx, || "2020-01-01".to_string());
   let end_date = use_state(cx, || "2023-12-31".to_string());
   let interval = use_state(cx, || "1d".to_string());
   let confidence_level = use_state(cx, || 0.95);
   let risk_free_rate = use_state(cx, || 0.04);
   let max_iterations = use_state(cx, || 1000);
   let objective_function = use_state(cx, || "max_sharpe".to_string());
   let chart_type = use_state(cx, || "optimization_chart".to_string());

   log::info!("{:?}", &symbols.current());
   log::info!("{:?}", &benchmark_symbol.current());
   log::info!("{:?}", &start_date.current());
   log::info!("{:?}", &end_date.current());
   log::info!("{:?}", &interval.current());
   log::info!("{:?}", &confidence_level.current());
   log::info!("{:?}", &risk_free_rate.current());
   log::info!("{:?}", &max_iterations.current());
   log::info!("{:?}", &objective_function.current());
   log::info!("{:?}", &chart_type.current());

   let chart = use_server_future(cx,&(symbols.current(), benchmark_symbol.current(), start_date.current(), end_date.current(),
                                interval.current(), confidence_level.current(), risk_free_rate.current(), max_iterations.current(),
                                objective_function.current(), chart_type.current()),
                      |(symbols, benchmark_symbol, start_date, end_date,
                           interval, confidence_level, risk_free_rate, max_iterations,
                           objective_function, chart_type)|{ async move{
          match get_portfolio_chart(
              symbols.to_string().split(",").map(|s| s.to_string()).collect(),
              benchmark_symbol.to_string(),
              start_date.to_string(),
              end_date.to_string(),
              interval.to_string(),
              *confidence_level,
              *risk_free_rate,
              *max_iterations,
              objective_function.to_string(),
              chart_type.to_string(),
          ).await {
              Ok(chart) => chart,
              Err(e) => format!("Error: {}", e),
          }
     }
   })?;

   log::info!("{:?}", &chart.value());

   cx.render(rsx! {
       h2 { "Portfolio Optimization" }

       form {
           onsubmit: move |e| {
               symbols.set(e.values["symbols"][0].to_string());
               benchmark_symbol.set(e.values["benchmark_symbol"][0].to_string());
               start_date.set(e.values["start_date"][0].to_string());
               end_date.set(e.values["end_date"][0].to_string());
               interval.set(e.values["interval"][0].to_string());
               confidence_level.set(e.values["confidence_level"][0].parse::<f64>().unwrap());
               risk_free_rate.set(e.values["risk_free_rate"][0].parse::<f64>().unwrap());
               max_iterations.set(e.values["max_iterations"][0].parse::<u64>().unwrap());
               objective_function.set(e.values["objective_function"][0].to_string());
               chart_type.set(e.values["chart_type"][0].to_string());
           },

           label { "Symbols" }
           input {
               r#type: "text",
               name: "symbols",
               value: "{symbols}",
           }
           br {}
           br {}

           label { "Benchmark Symbol" }
           input {
               r#type: "text",
               name: "benchmark_symbol",
               value: "{benchmark_symbol}",
           }
           br {}
           br {}

           label { "Start Date" }
           input {
               r#type: "date",
               name: "start_date",
               value: "{start_date}",
           }
           br {}
           br {}

           label { "End Date" }
           input {
               r#type: "date",
               name: "end_date",
               value: "{end_date}",
           }
           br {}
           br {}

           label { "Interval" }
           input {
               r#type: "text",
               name: "interval",
               value: "{interval}",
           }
           br {}
           br {}

           label { "Confidence Level" }
           input {
               r#type: "text",
               name: "confidence_level",
               value: "{confidence_level.to_string()}",
           }
           br {}
           br {}

           label { "Risk Free Rate" }
           input {
               r#type: "text",
               name: "risk_free_rate",
               value: "{risk_free_rate.to_string()}",
           }
           br {}
           br {}

           label { "Max Iterations" }
           input {
               r#type: "text",
               name: "max_iterations",
               value: "{max_iterations.to_string()}",
           }
           br {}
           br {}

           label { "Objective Function" }
           input {
               r#type: "text",
               name: "objective_function",
               value: "{objective_function}",
           }
           br {}
           br {}

           label { "Chart Type" }
           input {
               r#type: "text",
               name: "chart_type",
               value: "{chart_type}",
           }
           br {}
           br {}

           button {
               r#type: "submit",
               "Submit"
                },

           div {
               dangerous_inner_html: "{chart.value()}",
           }
       }
   })

}


#[server]
pub async fn get_portfolio_chart(
   symbols: Vec<String>,
   benchmark_symbol: String,
   start_date: String,
   end_date: String,
   interval: String,
   confidence_level: f64,
   risk_free_rate: f64,
   max_iterations: u64,
   objective_function: String,
   chart_type: String,
) -> Result<String, ServerFnError> {
   let pc = PortfolioCharts::new(
       symbols,
       &benchmark_symbol,
       &start_date,
       &end_date,
       Interval::from_str(&interval),
       confidence_level,
       risk_free_rate,
       max_iterations,
       ObjectiveFunction::from_str(&objective_function),
   ).await.unwrap();

   let chart = match chart_type.as_str() {
       "optimization_chart" => pc.optimization_chart().unwrap().to_html(),
       "performance_chart" => pc.performance_chart().unwrap().to_html(),
       "asset_returns_chart" => pc.asset_returns_chart().unwrap().to_html(),
       _ => pc.optimization_chart().unwrap().to_html(),
   };
   Ok(chart)
}

cargo.toml

[package]
name = "dioxus-practice"
version = "0.1.0"
edition = "2021"

[dependencies]
# Common dependancies
dioxus = "0.4.3"
dioxus-fullstack = "0.4.3"
serde = "1.0.195"
serde_json = "1.0.111"
log  = "0.4.20"
wasm-logger = "0.2.0"

# Web dependancies
dioxus-web = { version = "0.4.3", features=["hydrate"], optional = true }

# Server dependancies
axum = { version = "0.6.12", optional = true }
tokio = { version = "1.32.0", features = ["full"], optional = true }
finalytics = { version = "0.3.6", optional = true }

[features]
default = []
ssr = ["axum", "tokio", "dioxus-fullstack/axum", "finalytics"]
web = ["dioxus-web"]
@ealmloff ealmloff added bug Something isn't working web relating to the web renderer for dioxus fullstack related to the fullstack crate labels Feb 19, 2024
@jkelleyrtp jkelleyrtp added this to the 0.5.0: Signals milestone Feb 23, 2024
@jkelleyrtp jkelleyrtp self-assigned this Mar 6, 2024
@jkelleyrtp jkelleyrtp changed the title Inner HTML does not get re-rendered in Dioxus Full Stack use_server_future is not properly reactive Mar 9, 2024
@jkelleyrtp
Copy link
Member

Okay I spent a while digging into this - the original issue has been fixed but we have a new issue where use_server_future isn't properly reactive in a way that you'd expect.

This is because during hydration we don't actually call the server future so we don't know what its dependencies are.

We should at least poll it once to get a sense of its deps, but without firing off a request.

Either that, or serialize its dependencies, which seems harder but more resilient (ala qwik).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working fullstack related to the fullstack crate web relating to the web renderer for dioxus
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants