Skip to content

give me sample code for CRUD simple #365

@joesandiroz2

Description

@joesandiroz2

i search you docs about event . i experiment like this not work
can you give me sample about counter increment , or todo list

from fastapi import FastAPI
from fastapi.responses import HTMLResponse
from fastui import FastUI, AnyComponent, prebuilt_html, components as c
from fastui.events import PageEvent

app = FastAPI()

# Global state to hold the list of animals
data_animal = ['lion', 'elephant', 'tiger']

@app.get("/api/", response_model=FastUI, response_model_exclude_none=True)
def hello_world() -> list[AnyComponent]:
    animal_components = []

    # Create a Text component for each animal
    for animal in data_animal:
        animal_components.append(
            c.Div(
                class_name="m-2",
                components=[
                    c.Text(text=animal)
                ]
            )
        )

    return [
        c.Page(
            components=[
                c.Button(
                    text="Add Animal",
                    on_click=PageEvent(name="add_animal"),  # Trigger event to add animal
                    named_style="warning",
                ),
                c.Text(text="Animals:"),
                c.Div(
                    class_name="mt-3",
                    components=[
                        *animal_components, 
                    ]
                ),
            ],
            events={
                "add_animal": lambda: add_animal()  # Handle the event to add an animal
            }
        ),
    ]

def add_animal():
    # Add "macan" to the global animal list
    data_animal.append("macan")
    print(data_animal)

@app.get('/{path:path}')
async def html_landing() -> HTMLResponse:
    return HTMLResponse(prebuilt_html(title='Hello World FastUI Demo'))

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions