Can I call a canister function that have a variant as a parameter? How?

I guess this is a silly question but I need to learn somehow jajaj and I can’t find the answer in the forum/sdk docs.

Thanks in advance.

You can, but to answer the How, it would help to know from where you want to call it (e.g., Motoko, Rust, JavaScript, dfx command line)?

Thanks for answering.

I want to call a function (Motoko) from the frontend (React).

Motoko function example:
public shared({ caller }) func addForm ( title : Text, description : Text, fType: FType )

fType:
public type FType = {
#pub;
#priv;
};

Frontend call:
await loggedActor.addForm(“First”, “Testing”, “priv”);

Last parameter can’t be Text obviously, I assume that I have to receive the text in motoko and then use a switch to assign the right parameter but If you have a better way would be awesome.

You can pass it in from Javascript as an object with the property name matching the tag and null as its value, eg

await loggedActor.addForm(“First”, “Testing”, { priv: null });

(Aside, tags can also have data attached, in which case you would replace null with the data, eg the Motoko variant

type B = { #this: Text; #that: Nat }

could be passed in from Javascript as

{ this: “hello” }
)

2 Likes

Thanks!! Really helpful.