In the preceding code, we used an Object.assign() to merge the old state with the new state. We can do this even better by using the scan() operator on our dispatcher member, like so:
// NGRX-light/storeV.js
const Rx = require('rxjs');
class Store extends Rx.Subject {
constructor() {
super();
this.dispatcher = new Rx.Subject();
this.dispatcher
.scan((acc, curr) => ({ ...acc, ...curr }))
.subscribe(data => this.next(data));
}
dispatch(newState) {
this.dispatcher.next(newState);
}
}
const store = new Store();
store.subscribe(data => console.log('store', data));
store.dispatch({ name: 'chris' });
store.dispatch({ address: 'London' });
An important thing to note in the preceding code is that we removed the state member from the store. It's simply not needed as we only care about the latest value being emitted anyway.