Search code examples
rshinyshinyappsshiny-reactivity

executing a function in R shiny after user text input not working


I'm trying to call a function that will process the user's request and then generate an excel file. Code is simplified for debugging purposes but the idea is that I need to be able to run a function upon a click of a button but nothing happens after clicking the 'replace' button.

    library(shiny)
    library(DT)
    library(readxl)
    library(writexl)
    library(openxlsx)
    library(plyr)
    library(tidyverse)
    
    ##################
    search_func <- function(user_input) {
    
      
      hfi <- read_excel("path/to/file", col_names = FALSE, sheet = "One")
      
      hfi_cut <- hfi[-c(1:13),]
      
      hfi_cut[2,1] <- user_input
      
      write_xlsx(hfi_cut, path = "path/to/file/hfi_cut.xlsx")
    }
    ########################################
    
    ui <- fluidPage(
      h2("hfi"),
      textInput("query", "Watcha wanna replace it with, homie?"),
      actionButton("action", "replace"),
      downloadButton("dl", "Download")
    )
    
    
    
    server <- function(input, output, session){
      
      
      storage <- eventReactive(input$action, {
        search_func(input$query)
      })
      
      
      output$dl <- downloadHandler(
        filename = function() {paste("Search_Output.xlsx")},
        content = function(file) {file.copy(""path/to/file/hfi_cut.xlsx"", file)}
      )
    }
    
    
    shinyApp(ui = ui, server = server)

Solution

  • You probably are looking for observeEvent :

    observeEvent(input$action, {
        search_func(input$query)
    })
    

    Complete app code -

    library(shiny)
    
    ui <- fluidPage(
      h2("hfi"),
      textInput("query", "Watcha wanna replace it with, homie?"),
      actionButton("action", "replace"),
      downloadButton("dl", "Download")
    )
    
    
    
    server <- function(input, output, session){
    
    observeEvent(input$action, {
        search_func(input$query)
      })
      
      
      output$dl <- downloadHandler(
        filename = function() {paste("Search_Output.xlsx")},
        content = function(file) {file.copy("path/to/file/hfi_cut.xlsx", file)}
      )
    }
    
    
    shinyApp(ui = ui, server = server)