import produce from 'immer'; // in class ZooState ... @Action(FeedZebra) feedZebra(ctx: StateContext<ZooStateModel>, action: FeedZebra) { ctx.setState(produce((draft) => { draft.zebraFood.push(action.zebraToFeed); })); }
This approach can also allow for the creation of well named helper functions that can be shared between handlers that require the same type of update. The above example could be refactored to this:
// in class ZooState ... @Action(FeedZebra) feedZebra(ctx: StateContext<ZooStateModel>, action: FeedZebra) { ctx.setState(addToZebraFood(action.zebraToFeed)); } // defined elsewhere import produce from 'immer'; function addToZebraFood(itemToAdd) { return produce((draft) => { draft.zebraFood.push(itemToAdd); }); }