no_dice
no_dice

Reputation: 105

shinyApp with ui and server in separate files?

Right now my shinyApp is running with four separate R files. app.R, server.R, ui.R, and global.R. This apparently is an old way of doing things but I like how it organizes my code.

I need to use the onStart parameter in the shinyApp() function. Because of the way I've separated my files, it looks like R knows to load the four files together when running the Run App button in R Studio. This means my app.R file only contains runApp().

I can't seem to use the onStart parameter with runApp(). And when I try to create a shinyApp(ui, server, onStart = test()) object and pass it through runApp() it can't find the test function.

### in global.R
test <- function(){
  message('im working')
}
### in app.R
app <- shinyApp(ui, server, onStart = test())

runApp(app)

I found this in the R documentation. I'm not sure what they mean by using the global.R file for this?

enter image description here

https://shiny.rstudio.com/reference/shiny/latest/shinyApp.html

Thanks a ton, I hope this question makes sense.

Upvotes: 0

Views: 3718

Answers (1)

Muzammil Aziz
Muzammil Aziz

Reputation: 186

From what I understand, the functionality you want can be achieved by both shinyAppDir and shinyApp. You just have to use them correctly. If you have the 3 file structure namely, ui.R, server.R, and global.R. You should use shinyAppDir and not shinyApp. In global.R, you can define code you want to run globally, if it's in a function, you can define and then call that function inside the same file i.e. global.R. In order to run it using shinyAppDir, you need to give the directory where your application files are placed.

According to the same shinyApp reference you shared,

shinyAppDir(appDir, options = list())

If you want to use shinyApp instead, you need to have both ui and server inside the same file, and pass the object name to shinyApp function. Here, if you want to run some code globally, you need to first have that code defined inside a function in the same file, and then pass that function name as the onStart parameter. If your function name is test you need to pass it as shinyApp(ui, server, onStart = test) and not test(), but more importantly, you need to have all 3 (ui, server, and your global function i.e. test) inside the same file.

According to reference,

shinyApp(ui, server, onStart = NULL, options = list(),   uiPattern = "/", enableBookmarking = NULL)

Upvotes: 1

Related Questions