0

I have a valuebox in a Shiny dashboard, it is updating itself with ReactivePoll function. This value came from a SQL query.

enter image description here

I need to save every value when it is updated (that happens when there is a new record on the database), I will save these values in a vector. Therefore, this vector will be increasing in length every time when we have a new value in the value box.

Finally, I want to create a line char whit this vector.

Which Shiny function should I use?

Thanks!

1 Answers1

1

Sure. We can store the values in a vector in a reactiveValues, so we can update and access it from everywhere.

Adding to a vector is as simple as myvector <- c(myvector, mynewvalue).

Below is a minimal working example. It shows adding values to a vector and displaying that vector in valueBoxes and a plot. For simplicity we'll skip the reactivePoll part.

library(shiny)
library(shinydashboard)

ui <- dashboardPage(

    dashboardHeader(),
    dashboardSidebar(),
    dashboardBody(
    
        valueBoxOutput("myvaluebox_latest"),
        valueBoxOutput("myvaluebox_all"),
        
        numericInput("mynumericinput", "Enter a Value", min = 1, max = 10, value = 5),
        actionButton("myactionbutton", label = "Add to Value to Vector"),
        
        plotOutput("myplot")

    )
    
)

server <- function(input, output, session) {
 
    #Create a reactive to store our vector
    myreactives <- reactiveValues(
        
        myvector = NULL
        
    )
    
    #Runs when the button is pressed
    observeEvent(input$myactionbutton, {
        
        #Add the selected value to our vector
        myreactives$myvector <- c(myreactives$myvector, input$mynumericinput)
        
    })
    
    #Generate the valuebox for the latest data, runs when the vector changes
    output$myvaluebox_latest <- renderValueBox(

        valueBox(value = tail(myreactives$myvector, 1), subtitle = "Latest Value"),

    )
    
    #Generate the valuebox for the all the data, runs when the vector changes
    output$myvaluebox_all <- renderValueBox(

        valueBox(value = paste(myreactives$myvector, collapse = " "), subtitle = "All Values")

    )
    
    #Generate the plot
    output$myplot <- renderPlot({
        
        #Don't draw the plot when there is no data in the vector yet
        req(myreactives$myvector)
        
        plot(myreactives$myvector, type = "l")
        
    })
    
}

shinyApp(ui, server)
Ash
  • 1,463
  • 1
  • 4
  • 7