How to make filter drop downs reset to "All"?

I have a dataframe and drop downs for filtering it.

Problem: When I click my “Reset filters” button, it correctly updates the displayed dataframe to display all data, but I’ve been unable to make my filter dropdowns revert to displaying “All” (item: 0 in each drop down list).

I’ve played around with caching, session state and re-running.

How should I approach this?

Hi @SomeGuy. :wave:

Can you show a simple code snippet of what you tried? It doesn’t need to be a large example, just a simple, toy dataframe showing how you started creating your filter and clearing action.

The simple code below correctly resets the value of both filter dropdowns. I confirmed this by using st.write to display the drop down values, which both correctly showed as “All” after the reset_button is clicked.

if reset_button:
    filter1 = 'ALL'   # ALL is element 0 in the filters dropdown options. 
    filter2 = 'ALL'

My problem is that the two filter dropdowns are not updated to display their new values. Instead they still show whatever filter setting was selected prior to the reset button being clicked.

What’s the normal way to make the displayed dropdown values refresh to match their programmatically updated value?

To programmatically update widgets, assign a key to them. Their key and value become a pair Session State. If you need to set a default value, do so by initializing the key in Session State. (It’s generally easiest not to mix value and key if you are programmatically changing your widgets.)

This example shows how to work with programmatically changed widgets. It’s got a little extra boilerplate logic to work in a multipage app if you want to retain statefulness, but the premise is there:

  1. Initialize a key-value pair in Session State with the default value you want for your widget.
  2. Assign that key to the widget you want to control.
  3. Whenever you want to change the value of the widget (often in the callback of some other widget), update that key-value pair in Session State.
import streamlit as st

def set_to_A():
    st.session_state.items = ["A"]

if "items" not in st.session_state:
    st.session_state.items = ["A","B","C"]

st.multiselect("Items", ["A","B","C","D"], key="items")

st.button("Set to just A", on_click=set_to_A)

Thanks @mathcatsand. :+1:

I tried to set-up session state variables within my code, but it refused to accept that the session state variable had been initiated, despite it being defined at the top of my code.

Your code above works perfectly by itself, so I’ll just rebuild my page around that as it’s faster than debugging my code. Thx.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.