2

I want to use a reactive expression that can be updated in either of two ways. Below is a very simple example with either numeric input or a reset button to set the expression back to its original state (in practice the expression is more complex, so can't use reactive values). It seems that only the second definition of num is recognised, so in the example the numeric input is ignored).
What am I missing?
Many thanks!

ui <- fluidPage(
  numericInput("number", "Input", 1),
  actionButton("button", "Reset"),
  textOutput("check")
)
server <- function(input, output){
  num <- reactive({
    input$number
  })
  num <- eventReactive(input$button, {
    1
  })
  output$check <- renderText({
    num()
  })
}
shinyApp(ui, server)
Marcus
  • 21
  • 1

1 Answers1

0

Edit:

We can use observeEvent() with each input to update num().

library(shiny)

ui <- fluidPage(
  numericInput("number", "Input", 1),
  actionButton("button", "Reset"),
  textOutput("check")
)
server <- function(input, output) {
  num <- reactiveVal()

  observeEvent(input$number, {
    num(input$number)
  })

  observeEvent(input$button, {
    num(1)
  })

  observeEvent(c(input$button, input$number), {
    output$check <- renderText({
      num()
    })
  })
}
shinyApp(ui, server)
jpdugo17
  • 6,816
  • 2
  • 11
  • 23
  • Thank you @jpdugo17, but that getting me where I want. The reactive expression remains responsive only to the reset button, not the numeric input (as you can see by the fact that the output under the reset button doesn't respond to the the numeric input). Any further thoughts? Apologies if my earlier question wasn't clear. – Marcus Dec 03 '21 at 23:45
  • 1
    Should read "...that's *not* getting me where I want..." To clarify, my problem is getting the expression to respond to both inputs, not updating the numeric input. – Marcus Dec 04 '21 at 00:00
  • I edited the answer, please take a look. – jpdugo17 Dec 04 '21 at 00:08
  • If i'm not mistaken, you want that the output show the value from `input$number` and if the button is pressed the output should return to 1? – jpdugo17 Dec 04 '21 at 00:23
  • Well, the output is just my attempt to see what's going on with the reactive expression num (this is just a toy example), but yes, that's essentially it.The problem is that the reactive expression num() only ever responds to the reset button (so taking a value of one ). I want it to respond to the changes in the numeric input as well. You can see from the output that this isn't happening. I suspect that my approach (having two – Marcus Dec 04 '21 at 22:15
  • @Marcus take a look at the edit, i think we will get this eventually. – jpdugo17 Dec 04 '21 at 23:05
  • 1
    That does the trick! So simple I just couldn't see it. Thank you for your patience @jpdugo17. – Marcus Dec 05 '21 at 22:19