I am experiencing extremely odd behavior with st.query_params and multiselect.
A user can be redirected to the page with an option already set for the multiselect. However, I also want the app the actively set the query params, such that it is easy for users to share the page with one another.
However, when “deselecting”/clearing the multiselect it needs to be clicked twice in order for Streamlit to clear the query params and to clear the selection in the multiselect. I am running the app locally. Below is a reproducible example, currently running with the latest Streamlit version == 1.38.0:
I managed to fix it such that the query params are set both when selecting and deselecting an option. It is also passed to session state to control the “flow” of the report. See the code below:
import streamlit as st
def set_query_param(
url_key: str,
session_state_key: str,
):
if st.session_state[session_state_key]:
st.query_params[url_key] = st.session_state[session_state_key]
else:
st.query_params.clear()
del st.session_state[session_state_key]
st.set_page_config(page_title="Test")
query_params = st.query_params.to_dict()
options = ["Option_1", "Option_2", "Option_3"]
selected_option = st.multiselect(
label="Select Option",
options=options,
default=query_params.get("option", []),
max_selections=1,
key="selected_option",
on_change=set_query_param,
args=["option", "selected_option"],
)
st.write(f"session state: {st.session_state.selected_option}")
st.write(f"multiselect state: {selected_option}")
if any(st.session_state.selected_option):
st.session_state.run_report = True
else:
st.session_state.run_report = False
if not st.session_state.run_report:
st.warning("Please select an option")
st.stop()
st.success("Success")
Thanks for stopping by! We use cookies to help us understand how you interact with our website.
By clicking “Accept all”, you consent to our use of cookies. For more information, please see our privacy policy.
Cookie settings
Strictly necessary cookies
These cookies are necessary for the website to function and cannot be switched off. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms.
Performance cookies
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us understand how visitors move around the site and which pages are most frequently visited.
Functional cookies
These cookies are used to record your choices and settings, maintain your preferences over time and recognize you when you return to our website. These cookies help us to personalize our content for you and remember your preferences.
Targeting cookies
These cookies may be deployed to our site by our advertising partners to build a profile of your interest and provide you with content that is relevant to you, including showing you relevant ads on other websites.