reflex icon indicating copy to clipboard operation
reflex copied to clipboard

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

Open SlonSky opened this issue 1 year ago β€’ 2 comments

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

  • Define computed var that returns a list in the State.
  • Use that state var in rx.foreach
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):

  • Python Version: 3.12.2
  • Reflex Version: 0.5.5

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

SlonSky avatar Jun 25 '24 16:06 SlonSky

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

image

Lendemor avatar Jun 25 '24 19:06 Lendemor

@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.

picklelo avatar Jul 08 '24 18:07 picklelo