reflex icon indicating copy to clipboard operation
reflex copied to clipboard

How can I use String.join with pc.List[str]

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

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.

heumsi avatar Mar 11 '23 07:03 heumsi

Hi! Try using this method : def index() -> pc.Component: return pc.center( pc.text(" ".join([str(item) for item in State.nodes)]) )

AryanMankame avatar Mar 11 '23 17:03 AryanMankame

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

Alek99 avatar Mar 12 '23 04:03 Alek99