0

I want to save the value from username input if it doesn't exist in data frame, and render text if it already exists (for reprex purpose).

Rendering text part works perfectly, but I don't know how to save it and use it later. I want to save the value permanently, not only on current session

I've got this error:
Warning: Error in <-: invalid (NULL) left side of assignment

library(shiny)

ui <- fluidPage(
  textInput("username", "username"),
  actionButton("save", "Save!"),
  textOutput("confirmation")
)

server <- function(input, output, session) {
  
  df <- reactive(data.frame(column1 = "user1"))
  
  exist <- reactive(input$username %in% df()$column1)
  
  observeEvent(input$save, {
    if (exist() == TRUE) {
      output$confirmation <- renderText("Username already exists!")
    } else {
      df() <- rbind(df(), input$username) # <-- THIS dosn't work
    }
  })
}

shinyApp(ui, server)

EDIT: Thanks to @I_O answer, I figured out this solution
reactiveVal() keep the changes in current session.
write_csv() and read_csv() part, allows app to use previously saved usernames.

saved_df <- read_csv("C:\\Users\\Przemo\\Documents\\R\\leaRn\\Shiny\\Moodtracker\\testers\\test_safe.csv")

ui <- fluidPage(
  textInput("username", "username"),
  actionButton("save", "Save!"),
  textOutput("confirmation")
)

server <- function(input, output, session) {
  
  df <- reactiveVal(saved_df)
  
  exist <- reactive(input$username %in% df()$column1)
  
  observeEvent(input$save, {
    if (exist() == TRUE) {
      output$confirmation <- renderText("Username already exists!")
    } else {
      output$confirmation <- renderText("")
      df(rbind(df(), input$username))
      write_csv(df(), "C:\\Users\\Przemo\\Documents\\R\\leaRn\\Shiny\\Moodtracker\\testers\\test_safe.csv")
    }
  })
}

shinyApp(ui, server)
polipopik
  • 73
  • 4
  • Try `df(rbind(df(), input$username))`. The difference between updating a `reactiveVal` (like your df) and an item of `reactiveValues` is a little catchy: https://stackoverflow.com/questions/39436713/r-shiny-reactivevalues-vs-reactive –  Apr 15 '22 at 08:04
  • 1
    Thanks, I should use `reactiveVal()` instead `reactive()` in 1st place. This solution could check if the value exists **ONLY** in current seassion. So I added the `write_csv()` and `read_csv()` part, and now it's working like I wanted to :) – polipopik Apr 15 '22 at 08:57
  • ^^^ hope the /leaRn/Shiny/ **Moodtracker** went up accordingly :-) –  Apr 15 '22 at 09:06

0 Answers0