简体   繁体   中英

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.

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()})

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM