0

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?

Mandroid
  • 6,200
  • 12
  • 64
  • 134
  • Why wouldn't you simply use [scalajs-react Ajax](https://github.com/japgolly/scalajs-react/blob/master/doc/EXTRA.md#ajax). It already returns `Callback`. – Branislav Lazic Oct 04 '21 at 08:34
  • I tried that too. I see no change in behaviour. Code inside onComplete is never called. – Mandroid Oct 04 '21 at 13:03

1 Answers1

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