Skip to content

Instantly share code, notes, and snippets.

@hypebright
Created February 13, 2022 09:39
Show Gist options
  • Save hypebright/14e66fc68680fbf3b8e639333e77cd5c to your computer and use it in GitHub Desktop.
Save hypebright/14e66fc68680fbf3b8e639333e77cd5c to your computer and use it in GitHub Desktop.
Simple example for demonstrating setting a default value for a picker based on local storage
library(shiny)
ui <- fluidPage(
shinyjs::useShinyjs(),
# event handler in JavaScript: handles requests from R
# tells JavaScript to call the function and to pass it a message that it got from R
tags$head(
tags$script("
Shiny.addCustomMessageHandler('fetch-localstorage-item', function(message) {
const myitem = localStorage.getItem(message.key)
Shiny.onInputChange(message.input, myitem)
});
"),
selectInput('select_input',
label = 'Input',
selected = NULL,
choices = c('InputA', 'InputB', 'InputC', 'InputD'))
)
)
server <- function(input, output, session) {
observe({
# calling JavaScript function from Shiny (as defined in UI scripts) to send information to Shiny
session$sendCustomMessage(type = "fetch-localstorage-item", message = list(key = 'myKey', input = "myLocalStore"))
})
# When app loads, fetch key-value pair and update picker
observeEvent(input$myLocalStore, once = TRUE, {
req(input$myLocalStore)
print(paste0('Updating picker with information from local storage: ', input$myLocalStore))
updateSelectInput(session = session,
inputId = 'select_input',
selected = input$myLocalStore)
})
observeEvent(input$select_input, {
# Set item in local storage
shinyjs::runjs(glue::glue("localStorage.setItem('{key}', '{value}')",
key = 'myKey',
value = input$select_input))
})
}
shinyApp(ui, server)
@hypebright
Copy link
Author

In your browser, it looks like this (Safari example):
localstorage2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment