Hi everybody,
I'm making a shiny app to interact with a database, but I ran into problems if I use an action button more than once. The first time everything works as planned, the data gets submitted, the form cleared and the table showing the content updates. The second time I want to add something, the data does get submitted but the form doesn't clear and the table does not update. From the 3rd click on the form clears again but the table still doesn't update like it is supposed to.
What am I overlooking, does anyone here have a tip for me ?
I tried to create a reproducible example:
library(shiny)
library(shinyjs)
data(iris)
mydf <- c("Sepal.Length","123")
ui <- shinyUI(
fluidPage(
useShinyjs(),
h3("Factor value"),
uiOutput("factor_select"),
div(
id = "factor_value_form",
textInput(inputId="factor_value",
label = p("Enter the factors value:"),
value = ""),
actionButton(class="submit", "submit_factor_value_button",
label = "Submit data to the database"),
h3("Data currently in table:"),
# show factors in database, reactive
tableOutput('factor_value_table')
)
)
)
server <- shinyServer(function(input, output) {
# get list of factors in database, reactive on update
factor_list <- eventReactive(input$submit_factor_button, ignoreNULL = FALSE, {
colnames(iris)
})
# generate reactive dropdownlist
output$factor_select <- renderUI({
selectInput("factor_id", label=p("Select the factor to specify: "), factor_list() )
})
# create insert if submit button is clicked
observeEvent(input$submit_factor_value_button, {
insert <- c(input$factor_id, input$factor_value)
mydf <<- rbind(mydf,insert)
# empty form
shinyjs::reset("factor_value_form")
# tell user submission was successful
shinyjs::alert("The data was submitted")
# when using button second time, alert does appear, data gets submitted,
# but form does not reset and table doesn't update! 3rd time works again
})
# reactive query, refresh the table on submit button, but also show data
# before button is pressed by using ignoreNULL = FALSE
factor_value_info <- eventReactive(input$submit_factor_value_button, ignoreNULL = FALSE, {
mydf
})
# print table with database info queried above
output$factor_value_table <- renderTable({
factor_value_info()
})
})
shinyApp(ui, server)
Thanks for your time and kind regards,
Julie