16.5 Save data generated from user inputs
Modified from here https://stackoverflow.com/questions/63329561/r-shiny-load-data-in-to-form-fields-from-previously-persistent-stored-data. See also the links given in the answer to that question. There is a New button, which resets the user inputs. There is a Delete button, which I thought was supposed to delete entries but it doesn’t seem to work.
Code
library(shiny)
# Define the fields we want to save from the form
fields <- c("name", "used_shiny", "r_num_years")
outputDir <- "responses"
saveData <- function(data) {
# Create a unique file name
fileName <- sprintf("%s_%s.csv", as.integer(Sys.time()), digest::digest(data))
# Write the file to the local system
write.csv(
x = data,
file = file.path(outputDir, fileName),
row.names = FALSE, quote = TRUE
)
}
loadData <- function() {
# Read all the files into a list
files <- list.files(outputDir, full.names = TRUE)
data <- lapply(files, read.csv, stringsAsFactors = FALSE)
# Concatenate all data together into one data.frame
data <- do.call(rbind, data)
data
}
# 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) {
# When the Submit button is clicked, save the form data
observeEvent(input$submit, {
df = data.frame(name=input$name,
used_shiny = input$used_shiny,
r_num_years = input$r_num_years)
df
saveData(df)
})
# Show the previous responses
# (update with current response when Submit is clicked)
output$responses <- DT::renderDataTable({
input$submit
loadData()
})
}
)