Filtering variables #5940
-
|
I am struggling with understanding how to filter a variable in Reflex, for example, like the "target_submission" defined below: Whenever I try anything like list comprehension (or any other vanilla python approaches) to filter this, it throws the following error:
And when I try to use "rx.foreach", I have not found any documentation on how to filter objects inside it. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
there are two well supported ways of approaching this: 1. Use a computed varDefine an class TargetState(rx.State):
_target_submissions: list[Dict] = []
@rx.var
def filtered_submissions(self) -> list[dict]:
return {s for s in self._target_submissions if s.get("active")}
...
def index():
return rx.vstack(
rx.foreach(TargetState.filtered_submissions, lambda s: submission_card(submission=s)),
)This is preferable, because you can make your unfiltered data var a backend-only var (leading underscore) and avoid having it sent to the frontend; instead send only the (likely smaller) filtered dataset to the frontend and render it completely with This is also nice, because it keeps more of logic in "normal python", which is easier to understand and reason about. 2. use
|
Beta Was this translation helpful? Give feedback.
there are two well supported ways of approaching this:
1. Use a computed var
Define an
@rx.varmethod in your state that performs the needed filtering. Whenever the data or the filter criteria change, the computed var will be recalculated automatically.This is preferable, because you can make your unfiltered data var a backend-only var (leading un…