Mark Zhou Mark Zhou - 3 months ago 146
R Question

Add a page refresh button by using R Shiny

I'm making an app and I need to add a button to refresh page (same function to press F5). Is there anyone can share a piece of code to implement it?

Thanks a lot!

Answer

I do have a very simple and nice solution but it won't work for a file input.

Here's a solution that'll work for everything except a file input:

runApp(shinyApp(
  ui = fluidPage(
    shinyjs::useShinyjs(),
    div(
      id = "form",
      textInput("text", "Text", ""),
      selectInput("select", "Select", 1:5),
      actionButton("refresh", "Refresh")
    )
  ),
  server = function(input, output, session) {
    observeEvent(input$refresh, {
      shinyjs::reset("form")
    })
  }
))

When you press "Refresh", all inputs will be reset to their initial values.

But file inputs are very strange and it's hard to "reset" them. See here. You could hack some JavaScript together to try to almost kind of reset an input field if you want. Here's how you would perform an actual page refresh:

runApp(shinyApp(
  ui = fluidPage(
    shinyjs::useShinyjs(),
    shinyjs::extendShinyjs(text = "shinyjs.refresh = function() { location.reload(); }"),
    textInput("text", "Text", ""),
    actionButton("refresh", "Refresh")
  ),
  server = function(input, output, session) {
    observeEvent(input$refresh, {
      shinyjs::js$refresh()
    })
  }
))

Disclaimer: both these solutions use a package I wrote, shinyjs

Comments