I hope you can learn from this
- reactive() should be at the highest scope level of your server code, and not nested within other constructs
- observe/observeEvents are for sideeffects, not producing data, if you want to produce data use reactive/eventReactive
- you have complete control over the names of what you make, so try to avoid names like barcode_first2 ... meaningful names are preferred. (I used the names barcode_split,barcode_first, barcode_second, but I dont use barcode_first2 etc. )
p.s. I added some styling just for the fun of it .
library(shiny)
library(tidyverse)
library(qrcode)
# Define UI for application that draws a histogram
ui <- fluidPage(
headerPanel(title = "QR - Split and generate"),
sidebarLayout(
sidebarPanel(
textInput("barcode","Enter the Barcode",
value = "ERVERBERG;43tgebef"),
actionButton("button","GO")
),
mainPanel(
tags$style( HTML(" .mycontainer > div {border-style:groove;
width:15em;height:12em;padding:1em;}")),
div(style="display:flex;gap:7em;",
class="mycontainer",
div(tags$label(tags$u("Full")),
textOutput("barcode_full")),
div(tags$label(tags$u("First")),
textOutput("barcode_first"),
imageOutput("svgplot_1")),
div(tags$label(tags$u("Second")),
textOutput("barcode_second"),
imageOutput("svgplot_2"))
)
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output, session) {
barcode_split <- eventReactive(input$button,{
stringr::str_split(input$barcode,pattern = ";",simplify = TRUE)
})
barcode_first <- reactive({
pluck(req(barcode_split()) ,
1)
})
barcode_second <- reactive({
pluck(req(barcode_split()) ,
2)
})
QR_first <- eventReactive(barcode_first(),{
qrcode::qr_code(barcode_first())
})
QR_second<- eventReactive(barcode_second(),{
qrcode::qr_code(barcode_second())
})
rendfunc <- function(txt,qr){
tf <- tempfile(fileext = ".svg")
qrcode::generate_svg(qr, tf, size = 100, foreground = "black", background = "white", show = FALSE)
list(
src = normalizePath(tf),
contentType = "image/svg+xml",
width = 100, height = 100,
alt = paste("My QR code:", sQuote(txt, FALSE))
)
}
output$svgplot_1 <- renderImage({
qr <- req(QR_first())
txt <- shiny::isolate(req(barcode_first()))
rendfunc(txt,qr)
}, deleteFile = TRUE)
output$svgplot_2 <- renderImage({
qr <- req(QR_second())
txt <- shiny::isolate(req(barcode_second()))
rendfunc(txt,qr)
}, deleteFile = TRUE)
#outputs
output$barcode_full <- {(
renderText(input$barcode)
)}
output$barcode_first <- {(
renderText(req(barcode_first()))
)}
output$barcode_second <- {(
renderText(req(barcode_second()))
)}
}
# Run the application
shinyApp(ui = ui, server = server)