Reputation:
I have this code on a service:
private appState = {};
private state$;
constructor() {
this.state$ = new BehaviorSubject(this.appState);
}
setState(key: string, value: any, persist: boolean = false) {
this.appState[key] = value; // in Memory
this.state$.next(this.appState); // inform subscribers
if (persist) {
if (typeof value === 'object') {
localStorage[key] = JSON.stringify(value);
} else {
localStorage[key] = value;
}
}
}
Then on my component:
I first have a method that sets some data:
setCurrentState() {
this.appStateService.setState('state1', {name: 'Joe Patton', active: true});
}
Then another method where I want to update the above data:
updateCurrentState() {
this.appStateService.setState('state1', { active: false });
}
My problem is that with the updateCurrentState I want to just update the active field but it's replacing the whole object.
How can I just update the needed data?
Upvotes: 0
Views: 423
Reputation: 6005
Update the function to not replace the object, but update only the keys sent, like below
It uses the Spread syntax and checks if the value exists already
setState(key: string, value: any, persist: boolean = false) {
this.appState[key] = this.appState[key] ? {...this.appState[key],...value} : value; // check if exists, spread and update with value
this.state$.next(this.appState);
if (persist) {
if (typeof value === 'object') {
localStorage[key] = JSON.stringify(value);
} else {
localStorage[key] = value;
}
}
}
Upvotes: 1