Py.Cafe

maartenbreddels/

solara-localstorage

LocalStorage in Solara using a vue template

DocsPricing
  • app.py
  • localstorage.vue
  • 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
import solara
from typing import Callable

counter = solara.reactive(0)

@solara.component_vue("localstorage.vue")
def LocalStorage(key: str, value: str, on_value: Callable[[str], None] = None, debug: bool=False):
    ...


def set_initial_value(value: str):
    counter.value = int(value)


def increment():
    counter.value += 1


@solara.component
def Page():
    # note that the initial render will be with counter.value == 0
    print(counter.value)
    with solara.Card("LocalStorate example"):
        LocalStorage(key="my-counter", value=str(counter.value), on_value=set_initial_value, debug=True)
        solara.Button(f"Clicks: {counter.value}", on_click=increment)
        solara.Markdown("Refresh the embedded page to see that we remember the counter value")
localstorage.vue
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<template>
    <div>
        <div v-if="debug">
            <div>{{key}}={{value}} </div>
        </div>
        <div v-else style="display: none">
        </div>
    </div>
</template>
<script>
module.exports = {
    created() {
        if(this.debug) {
            console.log("localStorage store: created for", this.key, this.value);
        }
        const initialValue = this.readLocalStorage()
        if(initialValue !== null) {
            if(this.debug) {
                console.log("found initial value for localStorage store", this.key, "=", initialValue)
            }
            this.value = initialValue;
        } else {
            if(this.debug) {
                console.log("no initial value for localStorage store", this.key)
            }
            this.writeLocalStorage();
        }
    },
    methods: {
        readLocalStorage() {
            return localStorage.getItem(this.key)
        },
        writeLocalStorage() {
            if(this.debug) {
                if(this.value === null) {
                    console.log("removing key from localStorage");
                } else {
                    console.log("set localStorage value to", this.value);
                }
            }
            let exp = new Date(new Date().setFullYear(new Date().getFullYear() + 10)).toUTCString()
            if(this.value === null) {
                localStorage.removeItem(this.key)
            } else {
                localStorage.setItem(this.key, this.value)
            }
            if(this.storage_written) {
                this.storage_written()
            }
        }

    },
    watch: {
        value(v) {
            this.writeLocalStorage()
        }
    },
}
</script>