Py.Cafe

maartenbreddels/

solara-reactive-and-mutable-improved

Demo: Handling Mutable Data with Reactive Variables Using Solara Library

DocsPricing
  • app.py
  • requirements.txt
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# how to work with mutable data and reactive vars
import solara
import pandas

store = {"books": "3", "shelves": "2", "racks": "1"}  # inventory

# give a custom equals function will will always trigger a re-render
# when the store is updated
rstore = solara.reactive(store, equals=lambda a, b: False)


@solara.component
def MarkdownEditor(field: str):
    store = rstore.value
    value = store[field]

    def store_updater(newval):
        store[field] = newval  # we mutate, which is generally not recommended
        # but due to our custom equals, assigning the value to the reactive var will trigger a re-render
        rstore.set(store)
        print("updated", store)  # debug

    solara.InputText("value " + field, value=value, on_value=store_updater)
    solara.Markdown(value)


@solara.component
def OtherDisplay(store: dict):
    print("Render OtherDisplay")
    solara.Text(f"I am a child component showing the store: {store}")


@solara.component
def Page():
    print("Page render")
    store = rstore.value
    for fld in store.keys():
        MarkdownEditor(fld)
    print("showing as frame", store)
    df = pandas.DataFrame([[k, v] for k, v in store.items()], columns=["item", "value"])
    solara.DataFrame(df)
    # make a copy, so if we call it again, it sees the change between calls
    OtherDisplay(rstore.value.copy())
requirements.txt
1
2
3
4
solara==1.42.0
# available from version >=1.42
#https://py.cafe/gh/artifact/widgetti/solara/2267179885/dist/solara_ui-1.41.0-py2.py3-none-any.whl
pandas