Search code examples
rmongodbshinymongodb-atlasmongolite

Deal with sessions in shiny app/Mongo Atlas instance


I am buildiing a shiny app that connects to MongoDb Atlas instance using Mongolite package. This is my MWE (I don't mind sharing the access to my Mongo instance, it is just a test)

ui.R

  fluidPage(
    
    title = 'Select Table Rows',
    
    h1('A Client-side Table'),
    
    fluidRow(
      column(6, DT::dataTableOutput('x1')),
      column(6, plotOutput('x2', height = 500))
    )
    ,fluidRow(
      column(6,checkboxInput("chkBoxInp_ShowStopper","Showstopeer"))  
      ,column(6,textInput("txtInp_Description","Description"))
    )
    ,fluidRow(
      column(6,actionButton(inputId = "Insert", label = "Add"))  
      ,column(6,actionButton(inputId = "Refresh", label = "Refresh"))
    )  
  )

server.R

library(mongolite)
library(shiny)

mongo_db_user <<- "pavel"
mongo_db_password <<- "Semeolvido1"
mongo_clustername <<- "cluster0.ii3mw98.mongodb.net"

mongo_database <<- "ejemplo"
mongo_collection <<- "tracker"

url_path = sprintf("mongodb+srv://%s:%s@%s", mongo_db_user, mongo_db_password, mongo_clustername)

mongo_con<<-mongo(collection = mongo_collection,url = paste0(url_path,"/",mongo_database))    

function(input, output, session) {
  
  RV<<-reactiveValues()

  RV$track<<-mongo_con$find("{}")
  output$x1 = DT::renderDataTable(RV$track, server = TRUE)  
  
  observeEvent(input$Insert,{
    
    new_raidid<-as.numeric(max(mongo_con$find("{}")$raidid))+1        
    data <- data.frame(raidid = new_raidid, 
                       showstopper = input$chkBoxInp_ShowStopper,
                       description = input$txtInp_Description)    
    
    mongo_con$insert(data)        
    RV$track<<-mongo_con$find("{}")
    
  })  
  
  observeEvent(input$Refresh,{    
    RV$track<<-mongo_con$find("{}")        
  })   
  
}

You can access to this app in shinyapp.io: https://l72mtf-pav0l-llamocca.shinyapps.io/mongo/

enter image description here

This app works OK when I add some records from one computer.

My problem is when I connect to the app from 2 different computers at the same time. It seems that the buttons works only in the last computer I connect with. I mean, when I add one record from the second computer, that record appears in the datatable shown in the second computer, but it does not appear in the first computer eventhough clicking in "Refresh" button.

What I want is the records I add from any computer to be visualized in all the sessions. How can I achieve this?


Solution

  • Because you use <<- you are creating RV in the global environment here:

    RV<<-reactiveValues()
    

    This gets run each time a new session starts, overwriting the shared RV object each time. I'm not quite sure why, but this causes updates to only trigger an invalidation in the last session.

    To fix this, assign a separate RV for each session:

    RV <- reactiveValues()