lulu
lulu

Reputation: 25

How to set reactive value to default in R Shiny?

I have a problem with updating a reactive value in shiny.

So what my app basically does, is to save textInputs from the user. When the user decides to upload all text inputs, I want to reset the textInputs.

Following example code:

ui.R

ui <- fluidPage(
  sidebarPanel(
    textInput("words", "Please enter a word"), 

    actionButton("submit_new_word", "Save"), # this submits each single word
    textOutput("submitted_new_words"), # this show all submitted words

    actionButton("submit_upload", "Upload my Results") # this uploads all submitted words
  )
)

server.R

server <- function(input, output, session) {
  words_submitted <- paste("") # initial value 

  w_submitted <- eventReactive(input$submit_new_word, {
    words_submitted <- paste(words_submitted, " ", input$words)
    words_submitted <<- words_submitted

    updateTextInput(session, 
                    inputId = "words",
                    value = "") 

    return(words_submitted)
  }, ignoreNULL=FALSE)

  output$submitted_new_words <- renderText({
    w_submitted()
  })

  observeEvent(input$submit_upload, {
    # saveData(data_final) # upload, not needed for example here

    words_submitted <<- paste("")
  })
}

If you try this minimal example, you will see that the text inputs will be resetted, but only after the "Save" button is clicked again.

I however would like to have the text inputs to be resetted when the "submit_upload" button is clicked.

Does somebody have an idea?

Upvotes: 1

Views: 1638

Answers (1)

Pork Chop
Pork Chop

Reputation: 29387

You probably best to do it with some sort of reactive. The way shiny works is that if there is no reactivity attached to it wont invalidate (refresh) anything on the client side such as renderText

library(shiny)

ui <- fluidPage(
        sidebarPanel(
                textInput("words", "Please enter a word"), 

                actionButton("submit_new_word", "Save"), # this submits each single word
                textOutput("submitted_new_words"), # this show all submitted words

                actionButton("submit_upload", "Upload my Results") # this uploads all submitted words
        )
)

v <- reactiveValues()

server <- function(input, output, session) {
        v$words_submitted <- paste("") # initial value 

        observeEvent(input$submit_new_word, {
                v$words_submitted <- paste(v$words_submitted, " ", input$words)
                updateTextInput(session, inputId = "words",value = "") 
        }, ignoreNULL=FALSE)

        output$submitted_new_words <- renderText({
                v$words_submitted
        })

        observeEvent(input$submit_upload, {
                # saveData(data_final) # upload, not needed for example here
                v$words_submitted <- paste("")
        })
}

# Run the application 
shinyApp(ui = ui, server = server)

Upvotes: 1

Related Questions