0

I have an app component inside of a Yew project which is a Rust front-end framework. The syntax for fetching a GET request is still a bit of a mystery to me, for example, the rust-analyzer is complaining about books.clone();:

struct BookList
use gloo_net::http::Request;
use yew::prelude::*;
use yew::prelude::use_effect;

#[function_component(App)]
pub fn app() -> Html {
  let books: UseStateHandle<Vec<BookList>> = use_state(|| vec![]);

  async fn fetch_books() {
    let response: Vec<> Request::get("http://localhost:3000/books");
 
    let cloned_books = books.clone();
    cloned_books.set(response.data);
  }

  use_effect(|| {
    fetch_books()
  });
}

It is saying:

can't capture dynamic environment in an fn item use the || { ... } closure form instead

I am essentially trying to write what would be the equivalent to this in React:

function App() {
  const [books, setBooks] = useState([]);

  const fetchBooks = async () => {
    const response = await axios.get(
      'http://localhost:3000/books'
    );

    setBooks(response.data);
  };

  useEffect(() => {
    fetchBooks();
  }, []);

I am told I cannot run futures without use_async

but what I am not clear on and I have tried to do this, is how do I store the fetch(url) in a variable and then pass it to set()?

#[function_component(App)]
pub fn app() -> Html {
  let books: UseStateHandle<Vec<BookList>> = use_state(|| vec![]);

  let fetch_books = use_async(async {
    let response = fetch("http://localhost:3000/books");
  });

  let fetch_books = fetch_books.clone();
  fetch_books.set(response.data);

  use_effect(|| {
    fetch_books()
  });
}

However, I still get complaints from rust-analyzer.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Daniel
  • 14,004
  • 16
  • 96
  • 156
  • Please show the full error from `cargo check` (rust-analyzer now has a way to show it). Also, `let response: Vec<> Request` isn't valid Rust code - are you sure this is what you have? – Chayim Friedman Dec 28 '22 at 18:54
  • Nitpick: you don't need the double-import from `yew::prelude`. – Chayim Friedman Dec 28 '22 at 19:06
  • Your code is not going to work. Unlike JS, futures don't run by themselves. Combine the `use_effect()` with [`use_async()`](https://docs.rs/yew-hooks/latest/yew_hooks/fn.use_async.html). – Chayim Friedman Dec 28 '22 at 19:19
  • @ChayimFriedman, `use_async` utilizes `fetch(url)`, but I need to store that in a variable such as `response` and access the `data` in there when I run the `set()`. No matter how I do it, I keep getting errors from rust analyzer. – Daniel Dec 29 '22 at 02:38

0 Answers0