Merge pull request #131 from gbj/fix-3x-server-resource-fetching

Fix issue in which server-side resource are called 3x
This commit is contained in:
Greg Johnston 2022-11-29 06:14:22 -05:00 committed by GitHub
commit 5f58db40f0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 24 additions and 12 deletions

View File

@ -39,7 +39,8 @@ pub async fn get_todos(cx: Scope) -> Result<Vec<Todo>, ServerFnError> {
// this is just an example of how to access server context injected in the handlers
let req =
use_context::<actix_web::HttpRequest>(cx).expect("couldn't get HttpRequest from context");
println!("req.path = {:?}", req.path());
println!("\ncalling server fn");
println!(" req.path = {:?}", req.path());
use futures::TryStreamExt;
@ -55,6 +56,8 @@ pub async fn get_todos(cx: Scope) -> Result<Vec<Todo>, ServerFnError> {
todos.push(row);
}
println!(" returning todos\n");
Ok(todos)
}

View File

@ -70,15 +70,8 @@ where
T: Debug + Serializable + 'static,
Fu: Future<Output = T> + 'static,
{
#[cfg(not(feature = "ssr"))]
// can't check this on the server without running the future
let initial_value = None;
#[cfg(feature = "ssr")]
let initial_value = {
use futures::FutureExt;
let initial_fut = fetcher(source());
initial_fut.now_or_never()
};
create_resource_with_initial_value(cx, source, fetcher, initial_value)
}
@ -629,10 +622,26 @@ where
where
T: Serializable,
{
let fut = self.source.with(|s| (self.fetcher)(s.clone()));
use futures::StreamExt;
let (tx, mut rx) = futures::channel::mpsc::channel(1);
let value = self.value;
create_isomorphic_effect(self.scope, {
let tx = tx.clone();
move |_| {
value.with({
let mut tx = tx.clone();
move |value| {
if let Some(value) = value.as_ref() {
tx.try_send((id, value.to_json().expect("could not serialize Resource")))
.expect("failed while trying to write to Resource serializer");
}
}
})
}
});
Box::pin(async move {
let res = fut.await;
(id, res.to_json().expect("could not serialize Resource"))
rx.next().await.expect("failed while trying to resolve Resource serializer")
})
}
}