Laura
Laura

Reputation: 483

In R/Shiny how to re-inforce selection of an input (selectInput) by clicking a button

My question is a confusing but it is simple:

I have a selecInput with 11 options. I pre-selected the first one.

I need to update this same selection (first one) , something like re-selection what has been selected by shiny. To do this update I include a button that selects the first option, see the code below:

library(shiny)
library(ggplot2)
library(shinyWidgets)

ui <- fluidPage(
  selectInput(inputId = 'selection',
              label = 'options',
              choices= names(mtcars),
              selected = names(mtcars)[1]),
  
  actionBttn(inputId = 'update',"Update"),
  
  plotOutput(outputId = 'plot_1')
)

server <- function(input, output, session) {
  
  observeEvent(input$update,{
      updateSelectInput(session, inputId = "selection", selected = names(mtcars)[1])
    })
  output$plot_1 <- renderPlot({
    
    
    ggplot(mtcars, aes(x = .data[[input$selection]], y = mpg)) + geom_line()
  })
}

shinyApp(ui, server)

So, I want to "select again" the first option. The user will see the same chart after he clicks the button. He will see the chart been updated.

Upvotes: 2

Views: 230

Answers (1)

Waldi
Waldi

Reputation: 41220

The plot doesn't redraw after pushing the update button if data selection isn't modified by the update.
To force redraw, you could include input$update in renderPlot so that it triggers this function.
cat allows to check in console that plot update was done.

library(shiny)
library(tidyverse)
library(shiny)
library(shinyWidgets)

ui <- fluidPage(
  selectInput(inputId = 'selection',
              label = 'options',
              choices= names(mtcars),
              selected = names(mtcars)[1]),
  
  actionBttn(inputId = 'update',"Update"),
  
  plotOutput(outputId = 'plot_1')
)

server <- function(input, output, session) {
  
  observeEvent(input$update,{
    updateSelectInput(session, inputId = "selection", selected = names(mtcars)[1])
    cat('Update pressed \n')
  })
  output$plot_1 <- renderPlot({
    input$update # force update
    cat('Plot updated \n')
    ggplot(mtcars, aes(x = .data[[input$selection]], y = mpg)) + geom_line()
  })
}

shinyApp(ui, server)

Before modification, log in console shows:

Listening on http://127.0.0.1:6199
Plot updated 
Update pressed 
Update pressed 
Update pressed 

After modification:

Listening on http://127.0.0.1:6199
Plot updated 
Update pressed 
Plot updated 
Update pressed 
Plot updated 
Update pressed 
Plot updated 

Upvotes: 3

Related Questions