Reference single dictionary state var key in nested rx.foreach
Describe the Features It would be a huge help in managing datasets if it would be possible to do the following:
class MyState:
my_outer_list: list[list[Any]] = [[0, "a", "b"], [1, "c", "d"]]
my_inner_dict: dict[int, list[list[Any]]] = {0: [["e", "f"]], 1: [["g", "h"]]}
rx.foreach(
SupersetState.my_outer_list,
lambda o: rx.foreach(
SupersetState.my_inner_dict[o[0]],
lambda i: rx.text(i[0])
)
)
which, at the moment, it throws reflex.utils.exceptions.VarTypeError: Unsupported Operand type(s) for []: ObjectCastedVar, CustomVarOperation
when there is one-to-many relation between datasets this makes the code clear by avoiding temporary state variables and triggers in the UI other than computational efficiency. Example: without such a feature, to render a one-to-many relation I need:
- to use temporary state vars and/or UI triggers like buttons to keep track of what is the primary key
- when the trigger is triggered, save the filtered dataset in another state variable in order to render it this makes the code messy in case of multilevel one-to-many (A-many-B, B-many-C, C-many-D) and it would help a lot especially when all the datasets have to be retrieved with one api call (unfortunately not always we have control on the api). With such feature we could organise the datasets when the api call is made and keep it clean and ready to use in the state, in a dictionary, instead, without such feature it is needed to save the raw data and filter each time a trigger is triggered (by passing the primary keys).
the issue comes from my_outer_list: list[list[Any]] as when you do o[0] it cannot know what type that is aside from Any. that results in reflex being a bit pedantic and saying "you cannot index into a dict with ANY variable, it has to be str/int". You can tell reflex o[0] is going to be a number with .to(int).
rx.foreach(
SupersetState.my_outer_list,
lambda o: rx.foreach(
SupersetState.my_inner_dict[o[0].to(int)],
lambda i: rx.text(i[0]),
),
)