How can I use js.Value as argument to js.Global().Get

Trying with GO WebAssembly accessing the browser IndexedDB, with the below code I was able to create the ibdexedDB, but I got an error while trying to access it using js.Global().Get(dbx) or even trying to access this.result

//go:build js && wasm

package main

import (
	"fmt"
	"syscall/js"
)

var dbOk, dbErr js.Func
var db js.Value

func main() {
	fmt.Println("Hello WASM")
	db = js.Global().Get("indexedDB").Call("open", "Database", 1)

	dbOk = js.FuncOf(func(this js.Value, args []js.Value) interface{} {
		defer dbOk.Release()
/* Here I've an error */
		dbx := this.result
		fmt.Println("this is: ", dbx)
/**********************/
		js.Global().Call("alert", "ok.")
		return nil
	})
	db.Set("onsuccess", dbOk)

	dbErr = js.FuncOf(func(this js.Value, args []js.Value) interface{} {
		defer dbErr.Release()

		js.Global().Call("alert", "sorry.")
		return nil
	})
	db.Set("onerror", dbErr)
	
    /* This line is wrong, can not access `db` */
	js.Global().Get(dbx).Call("transaction", "readwrite").Call("objectStore", "employee").Call("add", `{ id: "00-01", name: "Karam", age: 19, email: "kenny@planet.org" }`)

	c := make(chan int)
	<-c
}

The error I got is:

# command-line-arguments
./wasm.go:21:14: this.result undefined (type js.Value has no field or method result)
./wasm.go:41:17: cannot use dbx (type js.Value) as type string in argument to js.Global().Get

To map it with JavaScript, I wanted this go:

	dbOk = js.FuncOf(func(this js.Value, args []js.Value) interface{} {
		defer dbOk.Release()
		dbx := this.result
		fmt.Println("this is: ", dbx)
		js.Global().Call("alert", "ok.")
		return nil
	})
	db.Set("onsuccess", dbOk)

To be equivalent to this JavaScript:

var dbx

request.onsuccess = function(event) {
    dbx = request.result;
    console.log("success: "+ dbx);
};

And this go code:

js.Global().Get(dbx).Call("transaction", "readwrite").Call("objectStore", "employee").Call("add", `{ id: "00-03", name: "Karam", age: 19, email: "kenny@planet.org" }`)

To replace this JavaScript code:

dbx.transaction(["employee"], "readwrite")
    .objectStore("employee")
    .add({ id: "00-03", name: "Karam", age: 19, email: "kenny@planet.org" });

Disclaimer: I have zero experience with syscall/js, but I think I see the problem:

You can’t say this.result on the Go side because this is just a js.Value and the js.Value type (in Go) either doesn’t have a result field, or if it does, it’s unexported (because it’s lower-cased), so you can’t access it.

To access a Javascript object’s property, such as this's result property, use js.Value.Get:

`this.Get("result")`
2 Likes

thanks, it worked perfectly

I resisted an overall sort of issue last time, I am now looking for some genuine arrangement.