Skip to main content

effect

Attribute Macro effect 

Source
#[effect]
Expand description

Marks an async method as a single effect that runs in the background.

§Basic usage

Define an async effect that runs in the background:

#[effect]
async fn timer_effect(&self, ctx: &Context) {
    loop {
        tokio::time::sleep(Duration::from_secs(1)).await;
        ctx.send(Msg::Tick);
    }
}

§With state

Effects can access component state:

#[effect]
async fn fetch_data(&self, ctx: &Context, state: MyState) {
    let url = &state.api_url;
    let data = fetch(url).await;
    ctx.send(Msg::DataLoaded(data));
}

§Multiple effects

You can define multiple effects on a component - they will all be collected into a single effects() method:

impl MyComponent {
    #[effect]
    async fn timer(&self, ctx: &Context) {
        // Timer logic
    }

    #[effect]
    async fn websocket(&self, ctx: &Context) {
        // WebSocket logic
    }
}

§Parameters

The function parameters are detected by position:

  • &self (required)
  • &Context (required) - any name allowed
  • State type (optional) - any name allowed

Note: Use the #[component] macro on the impl block to automatically collect all methods marked with #[effect] into the effects() method.