From 6e6a495b424860348634c047b4b3f5eda6dbf962 Mon Sep 17 00:00:00 2001 From: Mike Bush Date: Tue, 21 Apr 2020 15:37:52 +0200 Subject: [PATCH] Use an event to trigger the fetch The code now matched the text underneath it --- crate/guides/fetch.md | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/crate/guides/fetch.md b/crate/guides/fetch.md index 561a105..5f91859 100644 --- a/crate/guides/fetch.md +++ b/crate/guides/fetch.md @@ -30,6 +30,7 @@ impl Default for Model { } } + #[derive(Clone, Serialize, Deserialize, Debug)] pub struct Commit { pub sha: String, @@ -44,6 +45,7 @@ pub struct Branch { #[derive(Clone)] enum Msg { DataFetched(seed::fetch::ResponseDataResult), + FetchData, } fn fetch_data() -> impl Future> { @@ -53,6 +55,11 @@ fn fetch_data() -> impl Future> { fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders) { match msg { + Msg::FetchData => { + orders.perform_cmd(fetch_data()); + orders.skip(); + } + Msg::DataFetched(Ok(branch)) => model.branch = Some(branch), Msg::DataFetched(Err(fail_reason)) => { @@ -77,7 +84,7 @@ fn view(model: &Model) -> Node { } fn after_mount(_: Url, orders: &mut impl Orders) -> AfterMount { - orders.perform_cmd(fetch_data()); + orders.send_msg(Msg::FetchData); AfterMount::default() } @@ -89,10 +96,10 @@ pub fn render() { } ``` -On page load, we trigger an update in the `init` function using `Msg::FetchData`, -which points the `update` via `orders.perform_cmd` and a function we've created +After component mount, we trigger an update in the `after_mount` function by sending `Msg::FetchData`, +which instructs the `update` fn to use `orders.perform_cmd` and an async function we've created called `fetch_data`. This allows state to be -update asynchronously, when the request is complete. `skip()` is a convenience method that +updated asynchronously, when the request is complete. `skip()` is a convenience method that sets `Update::ShouldRender` to `Skip`; sending the request doesn't trigger a render. We pattern-match the response in the `update` function's`DataFetched` arm: If successful, we update the model. If not, we display an error in the console using the `error!` macro.