I'm new to Motoko and this code is giving me errors

53 Views Asked by At
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?

1

There are 1 best solutions below

0
On

It seems that you are looking for Array.append, however as it is deprecated, you should use Buffers with preupgrade and postupgrade instead of the following:

import Array "mo:base/Array";

actor {

  type Post = {
    id : Int;
    creator : Text;
  };

  stable var Posts = Array.init<Post>(1, { id = 0; creator = "" });

  func addPost(id : Int, creator : Text) : () {
    let NewPosts = Array.init<Post>(1, { id; creator });
    Posts := Array.thaw(Array.append(Array.freeze(Posts), Array.freeze(NewPosts)));
  };

};