Home > OS >  Check if js.Value exists
Check if js.Value exists

Time:11-17

In the JavaScript code, I've:

function readAll() {
    var objectStore = db.transaction("employee").objectStore("employee");
    
    objectStore.openCursor().onsuccess = function(event) {
       var cursor = event.target.result;
       
       if (cursor) {
          alert("Name for id "   cursor.key   ", Value: "   cursor.value);
          cursor.continue();
       } else {
          alert("No more entries!");
       }
    };
 }

In my equivalent GO code, I wrote:

    var ReadAll js.Func
    ReadAll = js.FuncOf(func(this js.Value, args []js.Value) interface{} {
        defer ReadAll.Release()
        cursor := this.Get("result")

        if cursor {
                _ = cursor.Get("key")
                value := cursor.Get("value")
                Window.Call("alert", value)
                cursor.Call("continue")

            } else {
                Window.Call("alert", "No more records")
            } 
        return nil
    })

    db.ObjectStore.Call("openCursor").Set("onsuccess", ReadAll)

But while compiling, I got:

non-bool cursor (type js.Value) used as if condition

Ho can I check if the related js.value exists or no?

CodePudding user response:

The javascript if(cursor) is checking if the value is truthy.

Your code this.Get result in a js.Value. It's not boolean, and you can't use it in a Go if clause.

The syscall/js package has Truthy() that you can use to mimick javascript truthy check.

https://pkg.go.dev/syscall/js#Value.Truthy

if cursor.Truthy() {
  ...
}

And to check if a value is falsey, you negate the result:

if !cursor.Truthy() {
  ...
}
  • Related