reflex icon indicating copy to clipboard operation
reflex copied to clipboard

pc.foreach iterates through an unknown list of values

Open demka-live opened this issue 2 years ago β€’ 1 comments

I am trying to make a simple web app that requests data from a database and prints it to the screen. I am using pynecone session module for this. Getting data

class MessageState(pc.State):
    @pc.var
    def messages(self) -> list[Messages]:
        with pc.session() as s:
            a = s.query(Messages).all()
            print(a)
            return a

Sending data to user

def index():
  return pc.container(
          pc.vstack(pc.foreach(MessageState.messages, render_message)))

rendering message

def render_message(message) -> pc.Component:
    print(f"MESSAGE TYPE{type(message)}")
    print(message)
    return pc.code(message.text)

And I always get a strange output in the console and a crash in the browser.

MESSAGE TYPE<class 'pynecone.var.BaseVar'>
{bjthrexz}

The app refuses to send messages to the render_message function and instead sends some random data. Any help would be appreciated.

demka-live avatar Feb 27 '23 19:02 demka-live

It is of type BaseVar because the value of a state var is not known at compile time. BaseVar is how we translate to javascript variables - so that weird string is just some JS variable name.

What does your print statement in the first example print? What is being rendered in the code component - the random string or nothing?

picklelo avatar Mar 03 '23 03:03 picklelo

I too am facing this issue. For example:

pc.foreach(State.users, lambda u: pc.text(str(u)))

This gives a list of random texts like {frvllirr}

r100-stack avatar May 15 '23 20:05 r100-stack

Using a print statement in the render function will be executed during compilation time.

This means the value that actually show up is the name of the variable used by the frontend to refer to those variables.

Similarly, if you force the conversion of str(u), you do that during compilation time (when the actual values are not known yet).

Lendemor avatar Jun 22 '23 16:06 Lendemor