Independent cache for each user session

Here is an example. Its only the beginning of an implementation. The challenge is that the localstorage is not available before the page has loaded.

import uuid
import panel as pn
import param
import uuid

pn.extension(sizing_mode="stretch_width", template="fast")

pn.state.template.param.update(site="Awesome Panel", title="How do I store user settings across reloads?")

class LocalStorage(pn.reactive.ReactiveHTML):
    value = param.Dict(default=None, allow_None=True)
    
    _template = """<div id="local-storage" style="display:hidden"></div>"""

    _scripts = {
        "render": """
if (data.value===null){
    data.value = JSON.parse(window.localStorage.getItem(model.name));
} else {
    window.localStorage.setItem(model.name, JSON.stringify(data.value));
}
""",
    "value": """
if (data.value===null){
    window.localStorage.removeItem(model.name);
} else {
    window.localStorage.setItem(model.name, JSON.stringify(data.value));
}      
"""
    }

    def clear(self, event=None):
        self.value = None

    def update(self, event=None):
        self.param.trigger("value")

# Use name as the "key" for localStorage in the browser
storage = LocalStorage(name="my-value")

clear = pn.widgets.Button(name="Clear Local Storage", button_type="primary")
clear.on_click(storage.clear)

update = pn.widgets.Button(name="Update Local Storage", button_type="primary")
update.on_click(storage.update)

pn.Column(
    """You can use the browsers `Local Storage`. Here is an example.""",
    storage, 
    storage.param.value,
    clear, update
).servable()

def get_local_storage():
    print("local storage", storage.value)

# The local storage value is not available before the app has loaded
pn.state.add_periodic_callback(get_local_storage, period=1000, count=1)


2 Likes