Google api spreadsheet issue

this is the template for applying google spreadsheet api that can insert user-entered data at the google spread sheet and load and show the table in developed app.

copying the code, it works but i don’t know why it doesn’t work if i place these functions at the very front of the script. it works only in a page and at once.

it works only at the subpage “A”

if select_event == "A":
  SCOPE = "https://www.googleapis.com/auth/spreadsheets"
      SPREADSHEET_ID = "MY SPREADSHEET_ID "
      SHEET_NAME = "Database"
      GSHEET_URL = f"https://docs.google.com/spreadsheets/d/{SPREADSHEET_ID}"

      @st.experimental_singleton()
      def connect_to_gsheet():
          # Create a connection object.
          credentials = service_account.Credentials.from_service_account_info(
              st.secrets["gcp_service_account"],
              scopes=[SCOPE],
          )
          # Create a new Http() object for every request
          def build_request(http, *args, **kwargs):
              new_http = google_auth_httplib2.AuthorizedHttp(
                  credentials, http=httplib2.Http()
              )
              return HttpRequest(new_http, *args, **kwargs)
  
          authorized_http = google_auth_httplib2.AuthorizedHttp(
              credentials, http=httplib2.Http()
          )
          service = build(
              "sheets",
              "v4",
              requestBuilder=build_request,
              http=authorized_http,
          )
          service = discovery.build('sheets', 'v4', credentials=credentials)
          gsheet_connector = service.spreadsheets()
          return gsheet_connector
  
  
      def get_data(gsheet_connector) -> pd.DataFrame:
          values = (
              gsheet_connector.values()
              .get(
                  spreadsheetId=SPREADSHEET_ID,
                  range=f"{SHEET_NAME}!A:E",
              )
              .execute()
          )
  
          df = pd.DataFrame(values["values"])
          df.columns = df.iloc[0]
          df = df[1:]
          return df
  
      def add_row_to_gsheet(gsheet_connector, row) -> None:
          gsheet_connector.values().append(
              spreadsheetId=SPREADSHEET_ID,
              range=f"{SHEET_NAME}!A:E",
              body=dict(values=row),
              valueInputOption="USER_ENTERED",
          ).execute()
  
          df = pd.DataFrame(values["values"])
          df.columns = df.iloc[0]
          df = df[1:]
          return df
  
      gsheet_connector = connect_to_gsheet()