Saving data in local storage via streamlit

I used streamlit-javascript ibrary to handle it:

from streamlit_javascript import st_javascript

def local_storage_get(key):
    return st_javascript(f"localStorage.getItem('{key}');")

def local_storage_set(key, value):
    value = json.dumps(value, ensure_ascii=False)
    return st_javascript(f"localStorage.setItem('{key}', JSON.stringify('{value}');")

The only problem was, that due to asynchronous nature of streamlit components, st_javascript did not provide return value of js code immidiatelly. Instead, it reloads some number of times before providing the value. And in case of None, you just don’t know if it returns empty value because you js code returns null or because the code execution hasn’t finished yet. So, the following code didn’t work

if "token" not in st.session_state:
    st.session_state.token = local_storage_get("token")

It just saved 0 - initial value of st_javascript component.

So, i build my own version of this lib, that allows distinguishing between “not ready yet” and “returns none” states.

Feel free to check it out here

Brief explanation:
It returns [] if the code execution is in progress and [] if it finishes. So, you can just st.stop() until result is not empty or for unblocking case, just check it before setting session_state value

if "token" not in st.session_state:
    if result := local_storage_get("token"): 
        st.session_state.token = result[0]