0

I want to make a reusable function that uses yewdux store, and call it in use_effect of another component. As per hook rule, hooks can only be used in top level of a function / hook

use crate::components::accounts::account_store::PhraseStore;
use yew::prelude::*;
use yewdux::prelude::*;

#[derive(Clone)]
pub struct SignTx {
    pub sign_tx: (),
}

#[hook]
pub fn use_sign_tx<T>(tx: T) -> SignTx
{
    let (store, _) = use_store::<PhraseStore>();

    let sign_tx = {
        wasm_bindgen_futures::spawn_local(async move {
            // code logic using store
            // api calls 
        });       
    };
    SignTx { sign_tx }
}

Now I want to call sign_tx function in another component?

#[function_component(TransactionFromHooks)]
pub fn transaction() -> Html {
    let first_load = use_state(|| true);
    use_effect(move || {
        if *first_load {
            wasm_bindgen_futures::spawn_local(async move {
                
               // Call the sign_tx function here
               // let sign = use_sign_tx(tx);
                
            });
            first_load.set(false);
        }
        || {}
    });

    html! {
        <h1>{"Transaction"}</h1>
    }
}

How to do it?

Amiya Behera
  • 2,210
  • 19
  • 32
  • Note `wasm_bindgen_futures::spawn_local` immediately returns `()` and runs the future you pass to it in the background, you probably want to make `use_sign_tx` an async function taking the `store` as parameter. – cafce25 Jan 03 '23 at 13:53
  • It gives error async function can't be hooks `pub async fn use_sign_tx` – Amiya Behera Jan 03 '23 at 14:01
  • * instead of a hook. – cafce25 Jan 03 '23 at 14:04
  • you said parameter, I kept yewdux store as super, and I don't want to make store parameter available in other component except the hook. yewdux store is not be available to a function that is not hook or functional_component – Amiya Behera Jan 03 '23 at 14:12
  • May be I can do that by calling the component onclick that has hook in top level. – Amiya Behera Jan 03 '23 at 14:46

0 Answers0