reflex
reflex copied to clipboard
How can I use String.join with pc.List[str]
How can I use the List[str] variable in State in a join function?
I initially tried the following.
"""Welcome to Pynecone! This file outlines the steps to create a basic app."""
from typing import List
import pynecone as pc
class State(pc.State):
nodes: List[str] = ["a", "b", "c"]
def index() -> pc.Component:
return pc.center(
pc.text(" ".join(State.nodes))
)
# Add state and page to the app.
app = pc.App(state=State)
app.add_page(index)
app.compile()
However, I got this error.
pc.text(" ".join(State.nodes))
^^^^^^^^^^^^^^^^^^^^^
TypeError: sequence item 0: expected str instance, tuple found
I also tried changing the code to look like this
class State(pc.State):
nodes: List[str] = ["a", "b", "c"]
@pc.var
def nodes_as_str(self) -> str:
return " ".join(State.nodes)
def index() -> pc.Component:
return pc.center(
pc.text(State.nodes_as_str)
)
But it still gives the same error.
pc.text(" ".join(State.nodes))
^^^^^^^^^^^^^^^^^^^^^
TypeError: sequence item 0: expected str instance, tuple found
How can I fix this?
I'm using python 3.11.0, pinecone 0.1.19.
Hi! Try using this method : def index() -> pc.Component: return pc.center( pc.text(" ".join([str(item) for item in State.nodes)]) )
You can't use methods like join on a State var see the var operations section for more details https://pynecone.io/docs/state/vars . I would recommend using a computed var for this functionality seems like a perfect use case. Lmk if that works for you
We are adding a better error message for this in the upcoming release, will be a more understandable error message that will point to the specific docs about var operations/computed vars