`onAdd` callback gets called multiple times
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!
Also happens with ArraySchema
Yeah happens to me too, we need an urgent fix :( This bug breaks the whole game
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
})