Streamlit App refreshing anytime I use the slider

I’m using streamlit to build a book recommendation website. The website has a feature to rate books from 1 to 5 and I’m using a slider to make this possible. The problem that I’m facing anytime I move the slider is that the page keeps on refreshing. Even when I don’t move the slider and click on the Submit Rating button which will store the rating in a database I created. Please how do I solve this issue of the page refreshing when I move the slider?

Code snippet:

st.cache_data
def get_rating():
return 1

if st.button(‘Show Recommendation’):
recommended_books, poster_url = recommend_book(selected_books)

for i in range(len(recommended_books)):
    st.text(recommended_books[i])
    st.image(poster_url[i])
    if st.button("Add to Favorites", key=f"add_to_favorites_{i}"):
        add_to_favorites(recommended_books[i])
        
    book_details = final_rating[final_rating["title"] == recommended_books[i]]
    if not book_details.empty:
        st.write("Genre:", book_details["genre"].values[0])
        st.write("Author:", book_details["author"].values[0])
        st.write("Publication Date:", book_details["year"].values[0])
    
    # Rating feature
    rating = st.slider("Rate the book (1-5)", min_value=1, max_value=5, value=get_rating(), key=f"rating_{i}")
    if st.button("Submit Rating", key=f"submit_rating_{i}"):
        book_id = book_details["book_id"].values[0]  
        store_rating(book_id, rating)
        st.experimental_set_query_params(rating_success="true")  # Set a query parameter to indicate successful rating storage

    st.markdown("---")

Check if a rating was successfully stored

if st.experimental_get_query_params().get(“rating_success”):
st.success(“Rating stored successfully.”)

1 Like

@Yasmin_Danmusa I would recommend using a slider inside a form to prevent refreshing the slider on every change:
see official streamlit documentation: st.form - Streamlit Docs

1 Like

hii. I tried it and it worked, thank you so much. but I have another problem; it doesn’t update the value of the slider even when I move it from 0. I move it to 5 for example, it stores it as 0 in the session state.

//code\

Create a SessionState object

class SessionState:
def init(self, **kwargs):
self.dict.update(kwargs)

Initialize session state

def init_session_state():
if “session_state” not in st.session_state:
st.session_state[“session_state”] = SessionState(
favorites=,
ratings={},
username=None,
login_successful=False
)
return st.session_state[“session_state”]

Retrieve or create session state

session_state = init_session_state()

Function to add a book to favorites

def add_to_favorites(book):
if book not in session_state.favorites:
session_state.favorites.append(book)
st.session_state[“session_state”] = session_state # Update session state
st.success(f"Book ‘{book}’ added to favorites.“)
else:
st.warning(f"Book ‘{book}’ is already in favorites.”)

# Store favorites in session state
st.session_state["favorites"] = session_state.favorites

Function to recommend books based on a selected book

def recommend_book(book_name):
books_list =
book_id = np.where(book_pivot.index == book_name)[0][0]
distance, suggestion = model.kneighbors(book_pivot.iloc[book_id, :].values.reshape(1, -1), n_neighbors=6)

poster_url = fetch_poster(suggestion)
isbn_list = final_rating.iloc[suggestion[0]]['ISBN'].values.tolist()

for i in range(len(suggestion)):
    books = book_pivot.index[suggestion[i]]
    for j in books:
        books_list.append(j)
return books_list, poster_url, isbn_list

Function to store a book rating in the database

def store_rating(isbn, rating, book_index):
try:
# Connect to the database
conn = psycopg.connect(
host=host,
port=port,
dbname=dbname,
user=user,
password=password
)

    # Create a cursor
    cur = conn.cursor()

    # Get the username from the session state
    username = session_state.username

    # Check if the user already exists in the userlist table
    cur.execute("SELECT username FROM bbdatabase.userlist WHERE username = %s", (username,))
    existing_user = cur.fetchone()

    if existing_user:
        # Check if the rating already exists for the user and book
        cur.execute("SELECT * FROM bbdatabase.ratings WHERE userid = %s AND isbn = %s", (username, isbn))
        existing_rating = cur.fetchone()

        if existing_rating:
            # Update the existing rating
            cur.execute("UPDATE bbdatabase.ratings SET rating = %s WHERE userid = %s AND isbn = %s",
                        (rating, username, isbn))
            st.success("Rating updated successfully.")
        else:
            # Insert a new rating
            cur.execute("INSERT INTO bbdatabase.ratings(rating, userid, isbn) VALUES (%s, %s, %s)",
                        (rating, username, isbn))
            st.success("Rating stored successfully.")
    else:
        st.error("User does not exist.")

    # Commit the changes
    conn.commit()

    # Update session state
    print("ISBN:", isbn)
    print("Rating:", rating)
    print("Book Index:", book_index)
    session_state.ratings[book_index] = rating


    # Update session state
   # session_state.ratings[book_index] = rating
    #st.session_state["session_state"] = session_state  # Update session state
    #st.session_state["ratings"] = session_state.ratings  # Update ratings in session state
    #session_state.ratings[book_index.item()] = rating
    session_state.ratings[int(isbn)] = rating
    st.session_state["session_state"] = session_state  # Update session state
    st.session_state["ratings"] = session_state.ratings  # Update ratings in session state



except (psycopg.Error, psycopg.DatabaseError) as e:
    st.error(f"Error storing rating: {e}")
finally:
    # Close the cursor and connection
    cur.close()
    conn.close()

Function to get the rating for a book

def get_rating(isbn):
return session_state.ratings.get(str(isbn), 0)

Update session state to store ratings

if “ratings” not in st.session_state:
st.session_state[“ratings”] = {}

@Yasmin_Danmusa can you just provide the minimal code needed to reproduce this issue? It is hard to read your code as text that isn’t formatted as code.

I would recommend you review a tutorial from Misra Turp, one of the Streamlit Ambassadors on how session states work with callback functions: How to use Streamlit session states and callback functions | Make your apps remember things! - YouTube

That should help you on your way.

Use below given javascript to resolve streamlit app refreshing

# JavaScript to keep the session alive
st.markdown(
    """
    <script>
    setInterval(function() {
        fetch(window.location.href);
    }, 3600000);  // 1 hour
    </script>
    """,
    unsafe_allow_html=True
)