Im new to Motoko and this code giving me errors

actor {

  type Post = {
    id : Int;
    creater : String;
  };

  stable var Posts : [Post] = [];

  func addPost(id : Int, creater : String) : () {
    Posts.push(id,creater);
  };

};

How can I push an object in that Mutable array that is defined as Posts

Array.append<Post>([{id=id;creater=creater;}],Posts}

but this method is deprecated, prefer to use Buffer instead

let buffer = Buffer.fromVarArray<Post>(Posts)
buffer.add({id=id;creater=creater;});
Posts := Buffer.toVarArray(buffer);

BTW, I don’t think there is “String” type in Motoko, it should be Text.

2 Likes

I’d recommend GitHub - ZhenyaUsenko/motoko-hash-map: Stable hash maps for Motoko . It preserves insert order so it can be used like an array and can be instantiates as a stable item so you won’t have to worry about regular upgrades…just type migrations.

Buffer isn’t stable.

1 Like