reflex-dev / reflex

🕸️ Web apps in pure Python 🐍
https://reflex.dev
Apache License 2.0
19.62k stars 1.12k forks source link

[REF-3192] rx.foreach over computed var list fails #3565

Closed SlonSky closed 1 week ago

SlonSky commented 3 months ago

Describe the bug

When I try to render list that is produced by computed state var, I encounter Server Error "TypeError: Cannot read properties of undefined (reading 'map')"

To Reproduce

import reflex as rx

class ExampleState(rx.State):

    @rx.var
    def items(self) -> list[str]:
        return list(str(i) for i in range(10))

def index():
    return rx.vstack(
        rx.foreach(
            ExampleState.items,
            lambda item: rx.text(item)
        )
    )

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

Expected behavior

the rx.foreach will render 10 text elements

Screenshots

image

Specifics (please complete the following information):

Additional context

Very similar to the old issue https://github.com/reflex-dev/reflex/issues/1886 and the same hack works:

import reflex as rx

class ExampleState(rx.State):

    @rx.var
    def items(self) -> list[str]:
        return list(str(i) for i in range(10))

def index():
    return rx.vstack(
        rx.cond(
            ExampleState.items,
            rx.foreach(
                ExampleState.items,
                lambda item: rx.text(item)   
            )    
        )   
    )

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

Also, everything works when the state var isn't computed (however it forces us to have some event handler that constatly updates the var):

import reflex as rx

class ExampleState(rx.State):
    items: list[str] = ['a', 'b', 'c']

def index():
    return rx.vstack(
        rx.foreach(
            ExampleState.items,
            lambda item: rx.text(item)   
        )    
    )

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

REF-3192

Lendemor commented 3 months ago

Tried to reproduce it on latest main, but your code snippet is working for me.

image
picklelo commented 3 months ago

@SlonSky I believe this is because somewhere your ExampleState.items is being set to None rather than an empty list. Then in Javascript, it's unable to call the map function leading to this error.