streamlit-javascript icon indicating copy to clipboard operation
streamlit-javascript copied to clipboard

Getitem not always work with Local storage

Open rajanant opened this issue 2 years ago • 1 comments

I want to store some data in local storage with javascript. But there is some problem - because getitem method always return 0.

Here is sample code:


import random

def rand_str():
    s = [chr(random.randint(ord('a'), ord('z'))) for _ in range(30)]
    return ''.join(s)


import streamlit as st
from streamlit_javascript import st_javascript

st.subheader("Javascript API call")

b1 = st.button('read')
if b1:
    # j_code = "console.log(localStorage.getItem('local_sandbox'));"
    j_code = "localStorage.getItem('local_sandbox');"
    v = st_javascript(j_code)
    st.session_state['text'] = f"Read from storage: {v}"

b2 = st.button('write')
if b2:
    j_code = f"""localStorage.setItem('local_sandbox', '{rand_str()}');"""
    v = st_javascript(j_code)
    st.session_state['text'] = f"Write to storage: {v}"

st.json(st.session_state)
print(f"{st.session_state.get('text')}")

Here is stdout: (1 press write, 2 press read, 1 write again, 2 read again)

Write to storage: 0
Read from storage: 0
Read from storage: 0
Write to storage: 0
Read from storage: 0
Read from storage: 0

in browser i can see that variable created - but getitem always return 0

if use string with console.log( - then in browser log shows correct values from storage

What is the reason of such behaviour?

rajanant avatar Aug 31 '22 10:08 rajanant

I am getting the same problem around here in my project. Do you have any updates on how to solve it?

tp-rbrasset avatar Jan 10 '23 21:01 tp-rbrasset