I am trying to go with the route of vanilla programming for my reactive needs.
Hence I choose Proxy, A wrapper over a object, where we can listen to changes in properties.
It has some traps, like get, set, has and so on. We are more interested in get so we can use it to update the UI
const Store = {
menu: null,
cart: [],
}
const proxiedStore = new Proxy(Store, {
set(target, property, value) {
target[property] = value
if(property === 'menu'){
window.dispatchEvent(new Event('menuchange'))
}
if(property === 'cart'){
window.dispatchEvent(new Event('cartchange'))
}
return true
}
})
export default proxiedStore
We have shared cart icon across the pages, when ever item is added to cart, our code dispatches cart change event which can be listened to update the UI. Which is our case to update the counter on the cart icon
But our cart is an array of items, which is made reactive by proxiedStore. So if I push new items to cart arrays I will get an update, which is not true.
Push changes the content of same array. Returning a new array will reflect a new change.
Similarly in case of removing an item, we should use filter method of Array.
That’s why redux patterns like NGRX always recommends to use immutable version of Array functions.