schema icon indicating copy to clipboard operation
schema copied to clipboard

`onAdd` callback gets called multiple times

Open tufcode opened this issue 2 years ago • 3 comments

SetSchema's onAdd callback gets called twice when it is inside a MapSchema.

export class MyRoomState extends Schema {
  @type({ map: Restaurant }) restaurants = new MapSchema<Restaurant>();
}
export class Restaurant extends Schema {
  @type({ set: Something }) objects: SetSchema<Something> = new SetSchema<Something>();
}
room.state.restaurants.onAdd((restaurant, restaurantKey) => {
   console.log("Restaurant added");
   restaurant.objects.onAdd(async (gameObject, objectKey) => {
      console.log("Oh hi there!")
   })
})

Now, if we look at browser console

Expectation

Restaurant added Oh hi there!

Reality

Restaurant added Oh hi there! Oh hi there!

tufcode avatar May 08 '23 15:05 tufcode

Also happens with ArraySchema

tufcode avatar May 08 '23 15:05 tufcode

Yeah happens to me too, we need an urgent fix :( This bug breaks the whole game

emre-sahinn avatar May 08 '23 15:05 emre-sahinn

Thanks for reporting, and sorry for the trouble!

A workaround, for now, is to provide false as a second argument to the inner onAdd, although this doesn't look nice. I will add tests for this and a proper fix soon!

This is due to onAdd now immediately triggering for existing items (in case of registering a callback late)

Workaround:

room.state.restaurants.onAdd((restaurant, restaurantKey) => {
   console.log("Restaurant added");
   restaurant.objects.onAdd(async (gameObject, objectKey) => {
      console.log("Oh hi there!")
   }, false) // here
})

endel avatar May 08 '23 16:05 endel