Appsilon / shiny.i18n

Shiny applications internationalization made easy
https://appsilon.github.io/shiny.i18n/
Other
168 stars 38 forks source link

showModal on load crashes app #59

Closed micahwilhelm closed 3 years ago

micahwilhelm commented 3 years ago

Hi there,

I've been using the shiny.i19n package (v0.1.0) to translate the app into multiple languages. However, after updating to v0.2.0 translations in a modal (that is shown once loading the app is finished) causes my app to crash. My app needs to shows a tutorial modal once the app is loaded. Any advice?

See my minimal, reproducible example below:

Works in v0.1.0 not in v0.2.0:

library(shiny)
library(shiny.i18n)

l <- Translator$new(translation_json_path = "www/translations.json")
l$set_translation_language("de")

ui = basicPage(
    actionButton("show", "Show modal dialog")
)

server = function(input, output) {

    dataModal <- function() {
        showModal(modalDialog(
            textInput("dataset", 
                                # "Choose data set", 
                                l$t("Choose data set"),
                                placeholder = 'Try "mtcars" or "abc"'
            ),

            footer = tagList(
                modalButton("Close")
            )
        ))
    }

    # Show modal when app is loaded
    dataModal()

    # Show modal when button clicked
    observeEvent(input$show, {
        dataModal()
    })

}
shinyApp(ui, server)

Gives error:

48: dataModal [/home/shinyuser/nccs/nccs_wp2/dev/test.R#14] 47: server [/home/shinyuser/nccs/nccs_wp2/dev/test.R#28] Error in .getReactiveEnvironment()$currentContext() : Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside a reactive expression or observer.)

dokato commented 3 years ago

Thanks @micahwilhelm for reporting that. I had a first look, but indeed this error looks a bit mysterious to me. I'll keep you updated once I figure that out.

rszymanski commented 3 years ago

Hi @micahwilhelm thank you for using the package and reporting the issue! In version 0.2.0 when the t method is run within a session it tries to retrieve the i18n-state input from the session (which can only be done within a reactive consumer for example reactive or observe).

In order to show the modal once the app is loaded you can use the ignoreNULL = FALSE argument of observeEvent which will cause the observer to run on startup (more info on the option is available here: https://shiny.rstudio.com/reference/shiny/1.5.0/observeEvent.html in the ignoreNULL and ignoreInit section)

  observeEvent(input$show, {
    dataModal()
  }, ignoreNULL = FALSE)

Please let me know if the described solution helps! :)