GithubHelp home page GithubHelp logo

jetli / yew-hooks Goto Github PK

View Code? Open in Web Editor NEW
159.0 2.0 13.0 29.39 MB

Hooks for Yew, inspired by streamich/react-use and alibaba/hooks.

Home Page: https://jetli.github.io/yew-hooks/

License: Apache License 2.0

Rust 100.00%
yew rust react hooks react-hooks wasm webassembly yew-hooks

yew-hooks's People

Contributors

aknarts avatar ctron avatar jetli avatar xfbs avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

yew-hooks's Issues

Bug in use_drop with nested target

I need to create a reproducer, but I think there is a bug in the use_drop when the ref is placed in a nested context:

#[function_component(Other)]
fn other(props: &ChildrenProps) -> Html {
  html!(<div> { for props.children.iter() } </div>)
}

#[function_component(Example)]
fn example() -> Html {
  let node = use_node_ref();
  let drop = use_drop(node.clone());

  html!(
    <div ref={node}> // works when it's here
      <Other>
        <div ref={node}> // but not when it's here
        </div>
      </Other>
    </div>
  )
}

Through the browser's DOM inspector, I can see the events being attached when putting the ref on the other one, but not when it's in the inner one.

use_async with a parameter from state

Assuming a use-case of:

  • Enter a parameter value
  • Issue the request (with that parameter)

It looks like with the current use_async variant, the future already gets created with every re-render, but not being used until the .run method is somehow invoked.

I think it would be nice to have some kind of "dependency" to the hook, which allows to provide one or more dependencies, parameters, which are being used to generate the future.

Something in the direction of:

#[function_component]
fn component() -> Html {
  let state = use_state_eq(String::new);

  let call = use_async(|input|{
    async move {
      fetch(input); // input = value of state
    }
  }, state.clone());

  let onclick = {
    let call = call.clone();
    use_callack(move |()|{
      call.run();
    })
  };

  html!() // somehow updates `state` (e.g. through an input field)
}

unexpected behavior of use_debounce

It seems that use_debounce returns a callback in a triggered state. That is, after the given time elapses the original callback is invoked whether or not the debounced version was ever invoked. This is not the behavior that I would expect. Is this the desired behavior for this hook?

The following code demonstrates:

use gloo_console::log;
use yew::prelude::*;
use yew_hooks::use_debounce;

#[function_component(App)]
fn app() -> Html {
  let f = use_debounce(|| {
    log!("this should never print, but it does");
  }, 1000);

  html! {}
}

fn main() {
  yew::Renderer::<App>::new().render();
}

How to store state from use_async via use_local_storage?

this is more of a request for clarification/help rather than a bug

i am trying to fetch data from a REST api once, and store it in local storage

at the moment, i have successfully fetched the data, and render it in html, but am unable to store it in local storage

relevant part of the code

#[function_component(Guest)]
pub fn guest() -> Html {
    let storage = use_local_storage::<String>("user".to_string());
    let state = use_async(async move { get_guest("https://matrix.org".to_owned()).await }); // get_guest returns Result<String, String>
    let get_guest_callback = {
        let state = state.clone();
        Callback::from(move |_| {
            state.run();
            let storage = storage.clone();
            if let Some(value) = &state.data {
                storage.set(value.to_string())
            }
        })
    };
    if let Some(value) = &*storage {
        //
    } else {
        get_guest_callback.emit("");
    }
    html! {}
}

compiler diagnostic

error[E0382]: borrow of moved value: `storage`
  --> src/components/atoms/guest.rs:40:27
   |
28 |     let storage = use_local_storage::<String>("user".to_string());
   |         ------- move occurs because `storage` has type `UseLocalStorageHandle<String>`, which does not implement the `Copy` trait
...
32 |         Callback::from(move |_| {
   |                        -------- value moved into closure here
33 |             state.run();
34 |             let storage = storage.clone();
   |                           ------- variable moved due to use in closure
...
40 |     if let Some(value) = &*storage {
   |                           ^^^^^^^^ value borrowed here after move
   |
   = note: borrow occurs due to deref coercion to `Option<String>`
note: deref defined here
  --> /home/isaac/.cargo/registry/src/github.com-1ecc6299db9ec823/yew-hooks-0.1.56/src/hooks/use_local_storage.rs:36:5
   |
36 |     type Target = Option<T>;
   |     ^^^^^^^^^^^

i am somewhat new to Rust, so there might be a feature that i've missed that could help solve this

Allow using multiple nodes with use_click_away

I am implementing a component consisting of two part: a toggle and some content. The content is shows using a portal.

I do want to use use_click_away, but actually both elements (the toggle and the portal content) should be considered "inside". This works when not using portals by wrapping with an additional element. However, this strategy fails when using portals.

If use_click_away would accept an array of nodes instead, I would be able to define two (or more) nodes as "inside" and it would work.

Let me know if you want me to work on a PR for this.

UseAsyncOptions::enable_auto() can lead to none of the options set

Hey!

I wanted to try out use_async with UseAsyncOptions::enable_auto. So I wrote code like:

    let db = use_async_with_options(
        [...],
        UseAsyncOptions::enable_auto(),
    );
    if db.loading {
        html! {
            <h1>{ "Loading…" }</h1>
        }
    } else if let Some(err) = &db.error {
        panic!("Unexpected error loading database:\n{err}");
    } else {
        let db: &Rc<basic_api::db::Db> = db.data.as_ref().unwrap();
        [...]
    }

As, intuitively, given the async is triggered ASAP, then at least one of the three options must be true.

However, it looks like there is a one-frame delay, and db.loading is set to false at the first run, along with error and data both being set to None.

I'm pretty new to yew_hooks, but… why is db.loading not set to true from the beginning if running with enable_auto? Is that a missing-feature oversight, a bug, or just something that's out of scope?

UseClipboardHandle's write_text is not working properly on Chrome on Mac.

I'm using the clipboard handle as an alternative to save files on an application. It seems to work across most browsers when I'm using it to write text to the user's clipboard, with the exception of Chrome on Mac. I checked if it was supported via the is_supported flag, and even have someone explicitly give the Clipboard API permission on the page but it still did not write text to the clipboard. Is there something I'm missing in terms of security issues, or is this a limitation on how the handle is implemented?

Can't access websocket from within callbacks

I'm trying to use the use_websocket_with_options hook to send a message immediately upon connecting to the server.

#[function_component(App)]
pub fn app() -> Html {
  let ws = yew_hooks::use_websocket_with_options(
    "ws://mywebsocket".into(),
    yew_hooks::UseWebSocketOptions {
      onopen: Some(Box::new(|_| {
        // This doesn't compile
        ws.send("test".into());
      })),
      ..Default::default()
    },
  );

  html! {
    <main>
    </main>
  }
}

How can I access ws from inside of this closure? UseWebSocketHandle doesn't have a way to change the websocket callbacks after initialization.

Update:

I managed to work around it using use_effect_with_deps:

let addr = "ws://mywebsocket";
let ws = use_websocket(addr.into());

{
  let ws = ws.clone();
  let ready_state = ws.ready_state.clone();
  use_effect_with_deps(
    move |ready_state| {
      if **ready_state == UseWebSocketReadyState::Open {
        info!("Open");
        ws.send("a".into());
      }
    },
    ready_state,
  );
}

use_async in combination with use_memo

I am wondering what the correct approach is to combine use_async with use_memo. The idea is to only reload when a dependency (passed to use_memo) has changed.

Making the `use_async` a bit more ergonomic

I really like this project, especially the use_async hook.

However, evaluating the state when rendering feels a bit verbose. It feels to me as if this could be improved a bit, using an enum.

If you are interested, I would try to come up with a PR, as basis for further refining it. Trying to keep the default API intact.

`use_websocket_with_options`, unintuitive reconnection_limit and unreliable reconnection

when reconnection_limit is set to None (or left as default), it will be set to 3. This number is not reflected in the docs and only exist in the code.

I think if it's set to None, it should allow infinite many retries.

Also, it makes the reconnection behavior very confusing. I don't know if it's a browser feature (I use Chrome), either connection seems to always fail when the tab is not active, or the timeouts are not executed when the tab is not active ,see this. For me, on production server, the connection does naturally break every now and then, so it is as if the websocket gets stuck at a disconnected state when I put the tab on the background for a few minutes and switch back to the tab.

I forked the code and removed the reconnection_limit altogether and it worked for me well. For any one else who have this issue, setting reconnection_limit to u32::MAX could be a temporary fix.

use_async error (the trait bound `impl yew::functional::hooks::Hook<Output = UseAsyncHandle<_, _>> + '_: Hook` is not satisfied)

I can't get what's the problem with trait bound when I try to use use_async hook:

let current_user = use_async(async move { api_users_me().await });

API function is

pub async fn api_users_me() -> Result<UserData, RequestError> {
    request_get::<UserData>("/api/users/me".to_string()).await
}

I get this error

error[E0277]: the trait bound `impl yew::functional::hooks::Hook<Output = UseAsyncHandle<UserData, RequestError>> + '_: Hook` is not satisfied
  --> src/client/user_context_provider.rs:20:21
   |
20 |     let current_user = use_async(async move { api_users_me().await });
   |                        ---------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |                        |
   |                        the trait `Hook` is not implemented for `impl yew::functional::hooks::Hook<Output = UseAsyncHandle<UserData, RequestError>> + '_`
   |                        required by a bound introduced by this call
   |
   = help: the trait `Hook` is implemented for `BoxedHook<'_, T>`

Nested State

Is there any way to achieve nested state on an object? For example with these data structures:

struct Coin {
    origin: String,
    value: u32,
    resell_value: u32,
    image_path: String
}

struct CoinCollection {
    name: String,
    coins: Vec<Coin>
}

I would like to be able to construct a state list and then when retriving a member variable of an object it should be another state object with reference to the underlying member. For example:

    let coin_collection: UseListHandle<CoinCollection> = use_list(vec![]);
    coin_collection.push(CoinCollection {
        name: "roman coins".to_string(),
        coins: vec![Coin {
            origin: "rome".to_string(),
            value: 10,
            resell_value: 300,
        }],
    });

    let coin_set: UseStateHandle<CoinCollection> = coin_collection[0];
    let roman_coins: UseStateHandle<Vec<Coin>> = coin_set.coins;

    // this value should would typically be set inside a function component from a callback.
    // but it should be reflected all the way up the "tree" in the `coin_collection` variable
    roman_coins[0].value.set(100);
    assert_eq!(coin_collection.current()[0].coins[0].value, 100);

Is there any way to achive this with yew-hooks? This idea is taken from react hookstate nested state.

`use_drop` returns stale data

When dropping a file and then something else, the files still seem to be present in the state. I don't see any way to figure out what the last dropped item is.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.