Multipage with session_state: Input only accepted on every second change?

Hi,

I am really struggling to understand the basic streamlit workflow. Why does this app only accept every second change in the text input field???

App structure:

.
├── app.py
└── pages
    └── page_1.py

app.py

import streamlit as st

"###### st.session_state:"
st.json(st.session_state, expanded=True)
st.divider()


"# Example App"
"Go to page 1 and enter some text."
"Change/enter the text in the text input => It works on the first change."
"Change/enter the text in the text input => It does **NOT** work on every second change!!!"
"Why are changes not accepted **on every second** change?? How to fix???"


if "text" in st.session_state:
    f"text: `{st.session_state.text}`"


st.divider()
"###### st.session_state:"
st.json(st.session_state, expanded=True)

page_1.py

import streamlit as st

"###### st.session_state:"
st.json(st.session_state, expanded=True)
st.divider()


if "text" not in st.session_state:
    st.session_state.text = "abc"


"# Page 1"


text_ti = st.text_input(label="Enter some text", value=st.session_state.text)
f"text_ti: `{text_ti}`"

st.session_state.text = text_ti


st.divider()
"###### st.session_state:"
st.json(st.session_state, expanded=True)

Ok, I found a solution myself. It is not very elegant, but it works.
I use st.text_input with a key (text_ti) and use a callback to write the key to the actual variable that I want to share between pages.

page_1.py

import streamlit as st


"###### st.session_state:"
st.json(st.session_state, expanded=True)
st.divider()


if "text" not in st.session_state:
    st.session_state.text = "abc"


"# Page 1"


def on_change_text_ti():
    st.session_state.text = st.session_state.text_ti


st.text_input(label="Enter some text", key="text_ti", value=st.session_state.text, on_change=on_change_text_ti)



st.divider()
"###### st.session_state:"
st.json(st.session_state, expanded=True)
``
1 Like

Thanks @FabK for also sharing your solution, callback functions can indeed resolve widget interactions requiring 2 interaction/clicks to update.

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