Saving radio session state when widget not rendered

I am trying to save the state of my app even when users are logged out. It seems that using the widget “key” does not save the state between runs if the widget is not rendered in the previous run per below.

import streamlit as st

def init_session_state(key, value):
  if not key in st.session_state:
    st.session_state[key] = value

init_session_state('logged_in', False)
init_session_state('radio_key', 'selection 1')

if st.session_state['logged_in'] == False:
  if st.button('Login'):
    st.session_state['logged_in'] = True
    st.experimental_rerun()
  st.stop()
else:
  if st.button('Logout'):
    st.session_state['logged_in'] = False
    st.experimental_rerun()

radio_selections = ['selection 1', 'selection 2']
radio_selection = st.radio('Radio Test:', radio_selections, key='radio_key')

radio_key

I tried saving the state in a separate session_state which works but then it glitches when changing the selection. I must click the selection twice to get it to select. Any ideas how to do this without this issue?

import streamlit as st

def init_session_state(key, value):
  if not key in st.session_state:
    st.session_state[key] = value

init_session_state('logged_in', False)
init_session_state('radio_idx', 0)

if st.session_state['logged_in'] == False:
  if st.button('Login'):
    st.session_state['logged_in'] = True
    st.experimental_rerun()
  st.stop()
else:
  if st.button('Logout'):
    st.session_state['logged_in'] = False
    st.experimental_rerun()

radio_selections = ['selection 1', 'selection 2']
radio_selection = st.radio('Radio Test:', radio_selections, index=st.session_state['radio_idx'])
st.session_state['radio_idx'] = radio_selections.index(radio_selection)

radio_session_state_glitch

I just opened a similar thread here: Make a widget remember its value after it is hidden and shown again in later script runs

Same problem for me, but different widget. :slightly_smiling_face:
Let’s hope someone will come up with a solution.

I have responded to your issue @Wally and this approach should work for @jonn26 too. Using callbacks eliminates the double click issue as well.