Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BaseState.get_var_value helper to get a value from a Var #4553

Merged
merged 3 commits into from
Jan 3, 2025

Conversation

masenf
Copy link
Collaborator

@masenf masenf commented Dec 18, 2024

When given a state Var or a LiteralVar, retrieve the actual value associated with the Var.

For state Vars, the returned value is directly tied to the associated state and can be modified.

Modifying LiteralVar values or ComputedVar values will have no useful effect.

Sample Code

from typing import ClassVar
import reflex as rx


class DataState(rx.State):
    categories: list[dict] = [
        {"id": 1, "name": "Maquinaria Agricola", "order": 0},
        {"id": 2, "name": "Tractores", "order": 0},
    ]
    frameworks: list[dict] = [
        {"id": 6, "name": "Reflex", "order": 0},
        {"id": 9, "name": "NextJS", "order": 0},
        {"id": 10, "name": "FastAPI", "order": 0},
        {"id": 11, "name": "Django", "order": 0},
    ]
    candies: list[dict] = [
        {"id": 1, "name": "KitKat", "order": 0},
        {"id": 2, "name": "Snickers", "order": 0},
        {"id": 3, "name": "Butterfinger", "order": 0},
    ]


class CategoryCarousel(rx.ComponentState):
    _target_var: ClassVar[rx.Var]

    async def handle_click(self, cat_id):
        print(f"Category clicked: {cat_id}")
        categories = await self.get_var_value(self._target_var)
        for c in categories:
            if c["id"] == cat_id:
                c["order"] += 1
                break

    @classmethod
    def get_component(cls, target: rx.Var[list[dict]], **props) -> rx.Component:
        cls._target_var = target
        props.setdefault("columns", "2")
        props.setdefault("width", "100%")
        props.setdefault("spacing", "4")
        return rx.grid(
            rx.foreach(
                target,
                lambda cat: rx.box(
                    rx.heading(f"ID: {cat['id']}"),
                    rx.text(f"Name: {cat['name']} {cat['order']}"),
                    on_click=cls.handle_click(cat['id']),
                    padding="1rem",
                    border="1px solid",
                    border_radius="lg",
                    margin_y="2",
                    shadow="md",
                ),
            ),
            **props,
        )


def category_boxes():
    return rx.container(
        rx.vstack(
            CategoryCarousel.create(target=DataState.categories),
            rx.separator(),
            CategoryCarousel.create(target=DataState.frameworks),
            rx.separator(),
            CategoryCarousel.create(target=DataState.candies),
            rx.separator(),
            CategoryCarousel.create(target=rx.Var.create([
                {"id": 1, "name": "Can", "order": 0},
                {"id": 2, "name": "You", "order": 0},
                {"id": 3, "name": "Edit?", "order": 0},
            ])),
            spacing="4",
            width="100%",
        ),
    )


def prueba_carousel():
    return rx.flex(
        category_boxes(),
        width="100%",
        min_height="100vh",
        padding_y="4em",
    )


def index():
    return prueba_carousel()


app = rx.App()
app.add_page(index)

When given a state Var or a LiteralVar, retrieve the actual value associated
with the Var.

For state Vars, the returned value is directly tied to the associated state and
can be modified.

Modifying LiteralVar values or ComputedVar values will have no useful effect.
reflex/state.py Outdated Show resolved Hide resolved
This requires rx.Field to pass typing where used.
reflex/state.py Outdated Show resolved Hide resolved
@masenf masenf merged commit 8477a1a into main Jan 3, 2025
41 checks passed
@masenf masenf deleted the masenf/get-var-value branch January 3, 2025 23:49
@benedikt-bartscher
Copy link
Contributor

@masenf this is awesome, thanks!

however it currently does not work with var operations over state vars, it seems like it just returns the value of the first state var used in the var operation. Do you want to get this fixed? I could (at least) create an issue for it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants