John Snow
John Snow

Reputation: 153

Shiny observeEvent duplicating output

I'm trying to build fullcalendar htmlwidget into my shiny app. However when I try to filter out underlying dataframe(with events) and output the calendar again using observeEvent, then the calendars are stacking up in main panel - example . How I can make old filter version go away and keep just current one?

server.R

library(fullcalendar)
library(shiny)


server <- function(input, output) {

  df<-data.frame(title = paste("Event", 1:3),
                 start = c("2017-03-01", "2017-11-15", "2017-11-16"),
                 end = c("2017-03-02", "2017-11-17", "2017-11-16"))

  observeEvent(input$typeInput, {
    df$title<-as.character(df$title)
    df<-df[df$title %in% input$typeInput,]
    f<- fullcalendar(data=df)
    output$calendar<-htmlwidgets::shinyRenderWidget(f, fullcalendarOutput,
    env=parent.frame(), quoted = TRUE)

    #output$calendar<-fullcalendar::renderFullcalendar(f)
  })
}

ui.R

library(shiny)
library(fullcalendar)

ui <- fluidPage(
  shinyjs::useShinyjs(),

   titlePanel("Test"),

   sidebarLayout(
      sidebarPanel(
        radioButtons("typeInput", "Product type",
                     choices = c("Event 3", "Event 2"),
                     selected = "Event 3")),

      mainPanel(
        fullcalendarOutput("calendar")
      )
   )
)

EDIT: I investigated more (web inspect of shiny form) and it seems that with each button change a new child of html widget is created (screenshot). I thought that with each observed change the widget is recreated (as observe event is re-ran) but it's not true. Is this default behaviour or it could be related also to some .js/.css files? Can I delete the widget and recreate it in observe event part?

Upvotes: 2

Views: 599

Answers (1)

Bertil Baron
Bertil Baron

Reputation: 5003

You want to use reactive rather than observeEvent. Also you don't need or want to place the assingnment to output variables within an observe or reactive function.

library(fullcalendar) 
library(shiny) 
server <- function(input, output) { 
df <- reactive({
  data.frame(title = paste("Event", 1:3), start = c("2017-03-01", "2017-11-15", "2017-11-16"), end = c("2017-03-02", "2017-11-17", "2017-11-16"))
}) 

f <- reactive({
  df <- df()
  df$title<-as.character(df$title) 
  df<-df[df$title %in% input$typeInput,] 
  fullcalendar(data=df)
})
 output$calendar<-htmlwidgets::shinyRenderWidget(f(), fullcalendarOutput, env=parent.frame(), quoted = TRUE) 

output$calendar<-fullcalendar::renderFullcalendar(f()) 
 }

Upvotes: 1

Related Questions