Yuriy
Yuriy

Reputation: 45

Setting default textInput value in R shiny via js (as result of js function)

I want to use R shiny app with js SDK of one social network. I want to get user id from js API and set it as default value for textInput form. But only once, for the first time.

The best result I managed to achieve using Shiny.onInputChange() function (or Shiny.setInputValue() for shiny>1.1)

Toy example:

ui <- fluidPage(

 textInput("uid",label = h4("Input ID"),value = "1"),
 actionButton("goButton", "Check this out!", class="btn-primary"),

 # getting user id via js
 tags$script(HTML(
  '
  uid = some_js_code;
  console.log("My uid - " + uid);

  // setting new value for input$uid variable
  Shiny.onInputChange("uid", uid);
  // for newer version of shiny 
  //Shiny.setInputValue("uid", uid);
  '
)

server <- function(input, output, session) {

  user<-reactive({

  input$goButton    
  user <- some_function_for_uid(input$uid)

  })

}

Problems:

  1. On first load of app value of variable "uid" is not changing. The value remains as it was in textInput function (value="1")

  2. Server function some_function_for_uid() receive new value of variable only when I press goButton. But value in text form still remains the same.

How correctly change default value in textInput and avoid described problems? Thank you in advance.

Upvotes: 0

Views: 1432

Answers (1)

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84699

To update the value in the textInput:

$("#uid").val(uid);

I don't know what you want to do with the button. Is it OK like this:

ui <- fluidPage(

  textInput("uid", label = h4("Input ID"), value = "1"),
  verbatimTextOutput("showUID"),
  #actionButton("goButton", "Check this out!", class="btn-primary"),

  tags$script(HTML(
    '
    uid = "hello";

    // setting new value in the textInput
    $("#uid").val(uid);

    // setting new value for input$uid variable
    Shiny.onInputChange("uid", uid);
    '
  ))

)

server <- function(input, output, session) {

  user <- eventReactive(input$uid, {
    rep(input$uid, 3)
  })

  output[["showUID"]] <- renderText({user()})

}

Upvotes: 1

Related Questions