Johann
Johann

Reputation: 97

Issue with shiny reactivity

I try to display the number of lines that matchs selecinput criteria with a possibility to add comment. Everytime someone add a comment, it s add a line, and i would like to update the number of line. (Actually i am working on a comment section where I want to display all the comments from a player and display every new comment submitted)

For the output$texte, when the selectinput changes, the df is subset, so the reactive works. When i have an observeEvent, df is saved, but there is no reactivity. when I switch the selected players, it never take into account the change in df, it's like he imports df once and never update it for the display.

Thanks for your help

df<-data.frame(nom=c("name1","name2","name3","name"1),
              comment=c("comment 1","comment 2","comment 3","comment4"))

ui<-  sidebarLayout(
        sidebarPanel(
          selectInput(
            inputId="select_j",
            label="choose name",
            choices=c("name1","name2","name3")
          )
        ),
        mainPanel(
          fluidRow(textOutput("texte")),
          fluidRow(textInput(
            inputId = "comment",
            label="Make a comment")),
          actionButton("submit", "Submit"))
    
)

server<-function(input,output){
  df_filter=reactive({df %>% subset(nom %in% input$select_j)})
  
  observeEvent(input$submit,{
    new_line=c(input$select_j,input$comment)
    df[nrow(df) + 1,] <- new_line
    write.csv2(df,"save.csv")
  })
  
  output$texte <- renderText({ 
    input$submit
    nrow(df_filter())
  })

}

shinyApp(ui, server)

Upvotes: 0

Views: 30

Answers (1)

Johann
Johann

Reputation: 97

I have found the solution (maybe not the only one).

The df has to be set as a reactiveVal and then update when observe event

df<-data.frame(
    nom=c("name1","name2", "name3"),
    comment=c("comment 1", "comment 2", "comment 3")
)

ui<-sidebarLayout(
    sidebarPanel(
        selectInput(
            inputId="select_j",
            label="choose name",
            choices=c("name1","name2","name3")
        )
    ),
    mainPanel(
        fluidRow(textOutput("texte")),
        fluidRow(textInput(
            inputId="comment",
            label="Make a comment")
        ),
        actionButton("submit", "Submit"))
    )

    server<-function(input, output) {
        df_r=reactiveVal(df)
        df_filter=reactive({
            df_r() %>% subset(nom %in% input$select_j)
        })
  
        observeEvent(input$submit,{
            new_line=c(input$select_j, input$comment)
            new_df<-rbind(df_r(), new_line)
            df_r(new_df) #update the reactive value
            write.csv2(new_df, "save.csv")
        })
  
        output$texte <- renderText({ 
            input$submit
            nrow(df_filter())
        })
    }

    shinyApp(ui, server)

Upvotes: 1

Related Questions