aghasemi / streamlit_js_eval

A custom Streamlit component to evaluate arbitrary Javascript expressions
MIT License
81 stars 12 forks source link

Calling get_geolocation() Multiple times causes duplicate widget error #11

Open GSeyfried opened 4 months ago

GSeyfried commented 4 months ago

In my app I get the users location off the bat, and store it in a session_state. I also have a button that refreshes the location, but when it's clicked I get error: raise DuplicateWidgetID( streamlit.errors.DuplicateWidgetID: There are multiple widgets with the same key='getLocation()'.

Init: loc = get_geolocation(key='init') if loc: st.session_state["latitude"] = loc['coords']['latitude'] st.session_state["longitude"] = loc['coords']['longitude']

Refresh: if st.button("Refresh Location"): loc = get_geolocation() if loc: st.session_state["latitude"] = loc['coords']['latitude'] st.session_state["longitude"] = loc['coords']['longitude'] st.rerun

In the docs I see that get_geolocation(component_key=None): I can create a unique key from a datetime object, but this seems roundabout. I just want a return of the current location without creating new widget objects. whatever.

aghasemi commented 4 weeks ago

Please check if the following code works:


import streamlit as st, random
from streamlit_js_eval import streamlit_js_eval, get_geolocation
import datetime, time

# Streamlit app
def main():
    loc = get_geolocation() 
    if loc: 
        st.session_state["latitude"] = loc['coords']['latitude'] 
        st.session_state["longitude"] = loc['coords']['longitude']        

    if st.button("Refresh Location"): 
        loc = get_geolocation(component_key=f"{time.time()}") 
        if loc:     
            st.session_state["latitude"] = loc['coords']['latitude'] 
            st.session_state["longitude"] = loc['coords']['longitude'] 
            st.rerun()

main()