Strange behavior with st.form and date_input when reading default values from a file

Hi @phoenix1790 :wave:

Thanks for sharing a reproducible example! I was able to repro the behavior on my end.

The root cause of the issue is that once the submit button is pressed and the data is dumped to JSON, the app does not rerun from top to bottom. Meaning the following code block isn’t run again, thereby using the old value of startDate from memory:

with open('data_update_date.json') as f:
    saved_dates = json.load(f)
    # strange behavior:
    startDate_default = datetime.datetime.strptime(saved_dates['startDate'], '%Y-%m-%d')
    # normal behavior:
    # startDate_default = datetime.date.today()

What you want to do is force a rerun so that your updated json file with the newly written startDate value is read into memory. To do so, define a callback function that updates your json file:

import datetime
import json
import streamlit as st

def update_date():
    with open("data_update_date.json", "w") as file:
        json.dump({"startDate": str(st.session_state.startDate)}, file)

with open("data_update_date.json") as f:
    saved_dates = json.load(f)
    startDate_default = datetime.datetime.strptime(saved_dates["startDate"], "%Y-%m-%d")

with st.form("dates"):
    start, update_button = st.columns((1, 1))
    startDate = start.date_input("Start Date", startDate_default, key="startDate")
    submitted = update_button.form_submit_button("Update data", on_click=update_date)

Best, :balloon:
Snehan

1 Like