rshinyshinydashboardr-googlesheets

Save Shiny output to Googlesheets


I have a shiny app which produces output I'd like to save to a Googlesheet. The app produces values based on user inputs and I've created a working mock-up (as abbreviated as I could) to replicate the error as seen in the code snippet box below.

I've also created a separate Google account for an example Googlesheet

Login for the Google account:

Username: public.thurston@gmail.com
Password: notapassword123
GoogleSheet: https://docs.google.com/spreadsheets/d/1y7dFTqUX3pLJ_VA-jjaWzMQydOVpwz8brPDMGpDCavk/edit#gid=0

library(shiny)
library(googlesheets)

#Code to download a new API token commented here:
#token = gs_auth(new_user = TRUE)
#saveRDS(token, "googlesheets_token.rds")

#Login to the following Google account:
#Username: public.thurston@gmail.com
#Password: notapassword123
#GoogleSheet: https://docs.google.com/spreadsheets/d/1y7dFTqUX3pLJ_VA-jjaWzMQydOVpwz8brPDMGpDCavk/edit#gid=0

ui <- shinyUI(navbarPage("Example",
  tabPanel("Example",
    sidebarLayout(
      sidebarPanel(
       numericInput("number", label = "I am the number input", value = 10),
       actionButton("saveresult", label = "Refresh & Save Result")        
      ), 
      mainPanel(
        h2(strong("Input value:")),
        h4(textOutput("text_number"))
      )
    )
  )
)
)

server <- shinyServer(function(input, output) {
  values <- reactiveValues()
  observe({
    input$saveresult
    values$number <- input$number
  })
  output$text_number <- renderText({
    input$saveresult
    paste("Number:", isolate(input$number))
  })
  observeEvent(input$saveresult, {
    gs_auth(token = "googlesheets_token.rds")
    gs_add_row(ss = gs_key("1y7dFTqUX3pLJ_VA-jjaWzMQydOVpwz8brPDMGpDCavk"), 
               ws = "Sheet1",
               input = output$text_number
    )
  })
})

shinyApp(ui = ui, server = server)

When I try to save the output to the Googlesheet I'm given the following error.

Warning: Error in $.shinyoutput: Reading objects from shinyoutput object not allowed.
Stack trace (innermost first):
    72: $.shinyoutput
    71: $
    70: nrow
    69: gs_add_row
    68: observeEventHandler [#13]
     4: <Anonymous>
     3: do.call
     2: print.shiny.appobj
     1: <Promise>
ERROR: [on_request_read] connection reset by peer

Solution

  • You can't read output value output$text_number so instead of input = output$text_number you can use input = values$number or input = input$number