0

I'm totally new in KotlinJs and I wanted to check its potential in server-less service development.

I decided to start with calling external API with HTTP GET method using XMLHttpRequest() suggested in KotlinJs documentation. However, I cannot come up with any way of using it without dynamic mechanism.

fun main(args: Array<String>) {

    val url = "https://jsonplaceholder.typicode.com/todos/1"

    var xhttp: dynamic = XMLHttpRequest()
    xhttp.open("GET", url, true)
    xhttp.onreadystatechange = fun() {
        if (xhttp.readyState == 4) {
            println(xhttp.responseJson)
        }
    }
    xhttp.send()
}

Of course this example works perfectly fine, but I feel like it has to be better way of doing it without disabling Kotlin's type checker.

  • Is there any way of doing it using KotlinJs only (without dynamic) ?
  • If it is not possible, could someone at least explain why?

1 Answer 1

0

I found a way for not using dynamic with callbacks, just like in classic .js

private fun getData(input: String, callback: (String) -> Unit) {

    val url = "https://jsonplaceholder.typicode.com/todos/$input"
    val xmlHttp = XMLHttpRequest()
    xmlHttp.open("GET", url)
    xmlHttp.onload = {
        if (xmlHttp.readyState == 4.toShort() && xmlHttp.status == 200.toShort()) {
            callback.invoke(xmlHttp.responseText)
        }
    }
    xmlHttp.send()
}

and than just call it:

getData("1") {
    response -> println(response)
}

Hopefully it will help someone in the future.

Sign up to request clarification or add additional context in comments.

3 Comments

Why don't you just use the fetch api? you can define it using the external keyword
Its actualy also good idea, however at that time I had been using this language few hours in total. Thanks for diffrent solution suggestion ;)
sure thing, If you need help defining the fetch api, I can write it down for you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.