It looks like you are trying to implement an editable code section using st_ace in a Streamlit application, and you're facing an issue where the code does not update as expected when you hit the save button. Here are some suggestions to help you resolve this problem:
1. Using Session State Properly
Ensure that the session state variable st.session_state.code is properly initialized before running the editor. If it is not initialized, it may lead to inconsistent behavior.
2. Handling the Form Submission
The way the form is handled can also cause issues. You might want to wrap your submission logic in the form_submit_button to accurately detect when the form is being submitted. Here's the adjusted code:
Example Code
import streamlit as st
from st_ace import st_ace
# Initialize session state
if 'code' not in st.session_state:
st.session_state.code = '# Your initial code here\n' # Default code
if 'show_editor' not in st.session_state:
st.session_state.show_editor = False
def st_form_button(label):
return st.form_submit_button(label)
# Your main component
def editor_component(title):
with st.form('editor_form', clear_on_submit=False, border=False):
markdown_section, edit_section = st.columns([0.7, 0.3], gap='large', vertical_alignment='top')
markdown_section.markdown(f'### {title}\n')
# Editor and Code View Toggle
if st.session_state.show_editor:
with edit_section:
toggle_button = st_form_button('💾 Save')
# Use the Ace editor
updated_code = st_ace(
value=st.session_state.code,
language='python',
theme='github',
keybinding='vscode',
min_lines=20,
max_lines=None,
font_size=14,
tab_size=4,
wrap=False,
show_gutter=True,
show_print_margin=True,
auto_update=True,
)
# Save button behavior
if toggle_button: # This is where you capture the form submission
st.session_state.code = updated_code
st.session_state.show_editor = False
st.success("Code saved successfully!")
else:
with edit_section:
toggle_button = st_form_button('✏️ Edit')
st.code(st.session_state.code, language='python')
if toggle_button:
st.session_state.show_editor = True
return st.session_state.code
# Call your function
editor_component("Editable Code Editor")
Key Changes Made
-
Form Submission Handling: The toggle_button captures the submission now, so you ensure that saving the code only occurs after pressing the "Save" button.
-
Success Notification: Added a success message to inform the user when the code is successfully saved.
-
Initialization Check: The session state for code and show_editor is initialized at the start of your script, which avoids potential errors if they are referenced before being set.
Testing the Changes
- Run your application with these changes and ensure that the code you input into the Ace editor is reflected properly upon clicking the save button.
- Make sure no errors are thrown while running the Streamlit application.
This modified structure should resolve the issue of seeing the previous code after making edits in the editor.