"Circular" reactivity question

I'm not sure what the best phrase in SWE is to describe such a problem, but I have come across a challenge recently on a few projects.

I am using leaflet to show a choropleth map of multiple locations. I also have a single trendline ggplot with a selectInput filtering the plot to one of said locations. When I click on an area on the map the selectInput is updated. But here's where the "circular" or two-way reactivity part comes in, I also want the map to "flyTo()" a location when I change the selectInput.

Implementing this causes issues of "double" reaction.

I can provide a reprex if needed but I feel this is a common problem outside of this literal example. Thanks in advance

a reprex would make it easier to understand your problem, and to provide you with a solution.

Here's a reprex of a set up that I thought was analogous to what you describe, but I don't see any substantial problem with it, and I set up it sort of 'naturally'.

library(shiny)
library(plotly)
gdata<- data.frame(
  a=c(1,3,2),
  b=c(2,4,4),
  c=c(3,2,1)
)
ui <- fluidPage(
  selectInput(inputId = "myselect",
              label = "selectinput",
              choices = letters[1:3]),
  div(style='display:flex;',
  plotly::plotlyOutput("general_plot",width = "300px",height="300px"),
  plotly::plotlyOutput("specific_plot",width = "300px",height="300px")
))

server <- function(input, output, session) {
  
  output$general_plot <- renderPlotly({
    
    gdata_long <- pivot_longer(gdata,
                 cols=everything(),
                 names_to = "name",
                 values_to = "value") %>% 
      mutate(mycol=case_when(name==req(input$myselect) ~ 'red',
             TRUE~'blue'))
    print("draw general")
    plot_ly(data=gdata_long,
            x=~name,
            y=~value,
            type="bar",
            color=~I(mycol)) %>% 
      event_register("plotly_click")
  })
  
  output$specific_plot <- renderPlotly({
    gd <- select(gdata,
                 req(input$myselect))
        plot_ly(data=gd,
            y=as.formula(paste0("~",input$myselect)),
            type="bar")
  })
  
  observe({
  d <- event_data("plotly_click")
  if(isTruthy(d))
    updateSelectInput(session=session,
                      inputId = "myselect",
                      selected=d$x)
  print(d)
  
  })
}

shinyApp(ui, server)
1 Like

Thank you, this example answered my question. You shouldn't have "one" reactive to do everything. You need to be explicit with the reactions and which way they connect, cheers!!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.