Is there any way to make this button smoother?

Hello, everyone!

I’m currently working on a Streamlit app and struggling to optimize a button. It’s an Add/Remove action button. When pressed, it triggers the app to rerun three times instead of once, resulting in the text below moving up and down, creating a laggy appearance. Is there any way to make this smoother? Thanks!

        if commodity_id in favorites:
            fav_button = st.button('❌Remove from Favorites', type='secondary', use_container_width=True)
            if fav_button:
                callbacks.on_remove_from_favorites(cookie_manager, commodity_id, favorites)
        else:
            fav_button = st.button('➕Add to Favorites', type='primary', use_container_width=True)
            if fav_button:
                callbacks.on_add_to_favorites(cookie_manager, commodity_id, favorites)

ezgif-4-89a28a95e7

streamlit==1.30.0
python==3.11.7
localhost

1 Like

Hi @maxam

You could use something like this:

mystate = st.session_state
if "btntxt" not in mystate: mystate.btntxt = ['Add', 'Rmv']
if "btnres" not in mystate: mystate.btnres = 0

def whn_clkd():
    if mystate.btnres == 0: mystate.btnres = 1
    elif mystate.btnres == 1: mystate.btnres = 0

mybtn = st.button(mystate.btntxt[mystate.btnres], key='bt', on_click=whn_clkd)

Cheers

2 Likes

Thanks!