Last active
October 11, 2022 09:04
-
-
Save daattali/c4db11d81f3c46a7c4a5 to your computer and use it in GitHub Desktop.
Basic form-submission shiny app used in "Persistent data storage in shiny apps" article http://deanattali.com/blog/shiny-persistent-data-storage/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(shiny) | |
# Define the fields we want to save from the form | |
fields <- c("name", "used_shiny", "r_num_years") | |
# Save a response | |
# ---- This is one of the two functions we will change for every storage type ---- | |
saveData <- function(data) { | |
data <- as.data.frame(t(data)) | |
if (exists("responses")) { | |
responses <<- rbind(responses, data) | |
} else { | |
responses <<- data | |
} | |
} | |
# Load all previous responses | |
# ---- This is one of the two functions we will change for every storage type ---- | |
loadData <- function() { | |
if (exists("responses")) { | |
responses | |
} | |
} | |
# Shiny app with 3 fields that the user can submit data for | |
shinyApp( | |
ui = fluidPage( | |
DT::dataTableOutput("responses", width = 300), tags$hr(), | |
textInput("name", "Name", ""), | |
checkboxInput("used_shiny", "I've built a Shiny app in R before", FALSE), | |
sliderInput("r_num_years", "Number of years using R", 0, 25, 2, ticks = FALSE), | |
actionButton("submit", "Submit") | |
), | |
server = function(input, output, session) { | |
# Whenever a field is filled, aggregate all form data | |
formData <- reactive({ | |
data <- sapply(fields, function(x) input[[x]]) | |
data | |
}) | |
# When the Submit button is clicked, save the form data | |
observeEvent(input$submit, { | |
saveData(formData()) | |
}) | |
# Show the previous responses | |
# (update with current response when Submit is clicked) | |
output$responses <- DT::renderDataTable({ | |
input$submit | |
loadData() | |
}) | |
} | |
) |
I'm using the same code but all my entries are NULL when the Submit Button is clicked. Any thoughts as to why this might happen?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi Dean,
can you explain how the bubbling trigger of the submit button is listened to and caught in the code chunk of rendering responses?
Why does the
input$submit
appear in therenderDataTable
part? I would rather see this as better suited case for anotherorberveEvent
.Also the
formData
seems not to be executed when the inputs stay the same, is it because of lazy loading? I figure this by adding a print statement to theformData
code:I think there a some internals hidden to my sight I would like to understand.