Making data sticky between pages when navigating back and forth


I building an app that allows a user to input a sql query on one page and then edit the results of the query on another page. I use session state to share data between the pages which works as intended, but the issue I run into is the user is on page 2 working with the data but the navigates back to page 1 the view the source query and resulting data, the page has reset and there is nothing there. Is it possible to make the session data sticky on each page until the user is complete and inputs a new source query on page 1?

If you have some data in a widget with a key, the that key in session state will get removed when the widget disappears (either from conditional display or moving to a different page). You either have to use a gimmick to interfere with the widget cleanup process or duplicate the data to a different key in session state that isn’t tied to a widget.

  1. Gimmick:
    For some widget with key='my_key', you can put at the top of every page:
st.session_state.my_key = st.session_state.my_key

What this does is prevent the key from being deleted when you move away from the page containing that widget. It interrupts the widget cleanup process, basically. It needs to be on every page because it needs to be on the page you go to for the first time when leaving the page with the widget.

  1. Duplicate the data
    For the same widget with key='my_key, copy the data to another key _my_key, for example in a callback.
def copy_data(key):
    st.session_state['_' + key] = st.session_state[key]

# Initialize data copy with default value
if '_my_key' not in st.session_state:
    st.session_state._my_key = 'whatever default value you want'

# Use data copy as the source of truth
st.session_state.my_key = st.session_state._my_key

st.text_area('Label', key='my_key', on_change=copy_date, args=['my_key'])