scalajs-react: Idiomatic way of processing ajax response

91 Views Asked by At

I am sending a GET request to backend rest service, as follows:

def showAllEmployees =  Callback {
    org.scalajs.dom.ext.Ajax.get(url = "http://localhost:8081/fetchAllEmployees").onComplete {
      case Success(xhr) => {
        Callback.log(xhr.responseText)
      }
      case Failure(t) => println("An error has occurred: " + t.getMessage)
    }
  }

I want to extract the records from the response. I observe that code inside case Success is not even executed.

So what is idiomatic way of doing it in scalajs-react?

1

There are 1 best solutions below

0
Artsiom Miklushou On
  1. You are wrapping your ajax call into Callback, it means in order to ex ecute it - you have to call .runNow()

  2. In case of Success response you are doing Callback.log(xhr.responseText) which is Callback that needs to evaluated again, but as you are inside onComplete which returns Unit - it is not possible to do. So, ether do Callback.log(xhr.responseText).runNow() or just use println

Working example:

def showAllEmployees =
  Callback {
    org.scalajs.dom.ext.Ajax
      .get(url =
        "https://run.mocky.io/v3/53993bf9-c589-4886-956b-e0b35a1ab13e"
      )
      .onComplete {
        case Success(xhr) =>
          Callback.log(xhr.responseText).runNow()
        case Failure(t) => println("An error has occurred: " + t.getMessage)
      }
  }