Robson Brandão Robson Brandão - 2 months ago 6
R Question

How to read a TextInput in ui.R, process a query with this value in global.R and show in server.R using Shiny

I have an application in Shiny R. On ui.R I read a Textinput, On global.R I process a query using sqldf().

How can I read a Textinput of ui.R in Global.R ?

ui.R

shinyUI(fluidPage(

#books <<- list("Descritores FOUSP" = "descritor"),

# Application title
titlePanel("CRAI"),

headerPanel(title="Pesquisa de Descritores"),
sidebarLayout(
sidebarPanel(

h5('Qual é o tema da sua pesquisa ?'),
textInput("descritor", "Digite um descritor",""),
submitButton('Pesquisar')
)
)


This textInput with name "descritor", I want to use in query on global.R

I tried this:

output$desc <- renderText({

paste(input$descritor)})

sql <- sprintf("SELECT * FROM csv WHERE Assuntos = '%s'", output$desc)


But I can´t to read "descritor" on global.R.

Answer Source

The file global.R is not part of the reactive section of a Shiny app. Only components defined inside a user interface and a server function can work as reactive expressions. Everything in global.R is carried out once at the launch of the app, but then not any more.

So if you want to have your sql statement carried out, you need the following inside your server:

sql <- reactive({
  sprintf("SELECT * FROM csv WHERE Assuntos = '%s'", output$desc)
})

mydata <- reactive({
  someSQLfunction(sql())
})

By making your SQL statement a reactive expression (function reactive() does that), it will get updated at every update of output$desc. This reactive expression behaves like a function(!). So the call sql() in the next statement will return the updated SQL statement. You can then use a function of your choice (I call it someSQLfunction) to process the statement.

You want to make the result of this statement also a reactive expression, so you can use it to create the relevant output of your app.