How can i change streamlit pages with buttons created within those pages

Hello Everyone, My streamlit app has two pages: 1. Home page with login forms and button 2. Feed page.
I currently use session state to enable me move data from one page to another, as well as change page. However, the problem I am facing now is I have to double-click my login button to switch screens and this is bad because they are certain actions my login function takes before switching screens and this affects how data is being handled and produces lots of errors.
I need to be able to effectively move pages and data without double-clicking.

I have tried st.rerun() but for some reason this doesn’t help either.

Below is a minimal reproducible code:

if "page" not in st.session_state:
    st.session_state.page = "home"
if "userid" not in st.session_state:
    st.session_state.userid = ""

def next(action, id):
    if action == "login":
        check = SQL.check_user_exists(id) # do some SQL stuff
        st.session_state.page = "feed" # Go to next page
        st.session_state.userid = id

placeholder = st.empty()

if st.session_state.page == "home":
    placeholder.empty()
    id = st.text_input("User ID",type="password",placeholder="4 digit pin (1234)")
    if st.button("login",on_click=next,args=("login",id)):
        pass

elif st.session_state.page == "feed":
    placeholder.empty()
    st.subheader("Feeds")
    print(st.session_state.userid)

I need to know what other methods I could use to achieve the same result. Thank you for your help.

Hi,

you may find this library interesting:

I don’t know if this could be what you are looking for.

page: feed.py

import streamlit as st

def show_feed_page(user_id):
    st.subheader("Test")
    st.write(f"User ID: {user_id}")
   

page: home.py

import streamlit as st

def show_home_page():
    st.title("Home Page")
    st.write("This is the home page content.")

app.py

import streamlit as st

from pages.home import show_home_page
from pages.feed import show_feed_page

# Mock database
class MockDatabase:
    users = {"1234": {"name": "David Oden", "email": "doden@xxxxx.com"}}

    @staticmethod
    def check_user_exists(user_id):
        return user_id in MockDatabase.users

if "page" not in st.session_state:
    st.session_state.page = "home"
if "userid" not in st.session_state:
    st.session_state.userid = ""

def login_action(id):
 
    user_exists = MockDatabase.check_user_exists(id)

    if user_exists:
        st.success(f"Login successful! Welcome, {MockDatabase.users[id]['name']}!")
        st.session_state.page = "feed"  # Go to the next page
        st.session_state.userid = id
    else:
        st.error("User not found. Please check your ID.")


with st.form(key="login_form"):
    id_input = st.text_input("User ID", type="password", placeholder="4 digit pin (1234)")
    login_button = st.form_submit_button("Login")

# Check if the form is submitted
if login_button:
    login_action(id_input)

# Render content based on the current page
if st.session_state.page == "home":
    if st.button("Go to Feed Page"):
        st.session_state.page = "feed"

    show_home_page()

elif st.session_state.page == "feed":
    if st.button("Go back to Home Page"):
        st.session_state.page = "home"

    show_feed_page(st.session_state.userid)

Will check it out Oscar, Thank you

Hello @David_Oden,

Here’s a revised strategy that ensures a single click on the login button initiates the transition to the feed page, leveraging Streamlit’s session state more effectively:

import streamlit as st

def check_user_exists(user_id):
    # Simulate checking the database for the user ID
    # Return True if user exists, False otherwise
    return user_id == "1234"  # Example condition

if "page" not in st.session_state:
    st.session_state.page = "home"

if "userid" not in st.session_state:
    st.session_state.userid = ""

def login(user_id):
    if check_user_exists(user_id):
        st.session_state.page = "feed"
        st.session_state.userid = user_id
        st.experimental_rerun()
    else:
        st.error("User ID not found.")

if st.session_state.page == "home":
    user_id = st.text_input("User ID", type="password", placeholder="4 digit pin (1234)")
    if st.button("Login"):
        login(user_id)

elif st.session_state.page == "feed":
    st.subheader("Feeds")
    st.write(f"Welcome, User ID: {st.session_state.userid}")

Hope this helps!

Kind Regards,
Sahir Maharaj
Data Scientist | AI Engineer

P.S. Lets connect on LinkedIn!

➤ Want me to build your solution? Lets chat about how I can assist!
➤ Join my Medium community of 30k readers! Sharing my knowledge about data science and AI
➤ Website: https://sahirmaharaj.com
➤ Email: sahir@sahirmaharaj.com
➤ 100+ FREE Power BI Themes: Download Now

3 Likes