Skip to content

rx.window_event_listener sends event to wrong state #6449

@tim-haselhoff

Description

@tim-haselhoff

Describe the bug
A clear and concise description of what the bug is.

rx.window_event_listener breaks when using on multiple pages.
Events seem to be sent to the first one registered.

To Reproduce
Steps to reproduce the behavior:

  • Code/Link to Repo:
import reflex as rx
from rxconfig import config

class State(rx.State):
    """The app state."""

    val: int = 0

    @rx.event
    def on_key_down(self, event: str):
        """Handle key down events."""
        print(f"Key down: {event}")
        if event == "ArrowRight":
            self.val += 1
        elif event == "ArrowLeft":
            self.val -= 1

    @rx.event
    def navigate_to_second_page(self):
        """Navigate to the second page."""
        return rx.redirect("/second")


def index() -> rx.Component:
    # Welcome Page (Index)
    return rx.container(
        rx.text(State.val),
        rx.window_event_listener(on_key_down=State.on_key_down),
        rx.button("Go to second page", on_click=State.navigate_to_second_page),
    )


class StateTwo(rx.State):
    """The app state for the second page."""

    val: int = 0

    @rx.event
    def on_key_down(self, event: str):
        """Handle key down events."""
        print(f"Key down on second page: {event}")
        if event == "ArrowRight":
            self.val += 1
        elif event == "ArrowLeft":
            self.val -= 1

    @rx.event
    def navigate_to_index(self):
        """Navigate back to the index page."""
        return rx.redirect("/")


def second_page() -> rx.Component:
    # Second Page
    return rx.container(
        rx.text(StateTwo.val),
        rx.window_event_listener(on_key_down=StateTwo.on_key_down),
        rx.button("Go back to index", on_click=StateTwo.navigate_to_index),
    )


app = rx.App()
app.add_page(index)
app.add_page(second_page, route="/second")

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Specifics (please complete the following information):

  • Python Version: 3.14.4
  • Reflex Version: 0.9.1
  • OS: Linux
  • Browser (Optional): Chromium

Additional context
Add any other context about the problem here.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions