'Angular Typescript Save previous value of a variable to restore data
I'm doing some operation on a variable modifying its data but I'd like to save it in another variable to be able to restore it if needed. I tried to declare my two variables in my class as below
user: User;
savedUser: User;
and to assign them in the constructor
this.user = data.user;
this.savedUser = data.user;
I have a function in the OnInit block that does the user operation
ngOnInit(): void {
this.user = this.formatUser(this.user);
}
formatUser(user:User): User{
user.name = 'Peter';
user.age = 18;
return user;
}
resetUser(): void {
this.user = this.savedUser;
}
The reset function is not working as it seems the "savedUser" variable is also updated when the line this.user = this.formatUser(this.user); runs
What am I doing wrong?
Thanks
Solution 1:[1]
You need to clone deep the initial user object instead of simply storing it in another variable. Every time you update savedUser just do like below.
const savedUser = {...data.user}
OR
const savedUser = Object.assign({}, data.user);
OR
const savedUser = JSON.parse(JSON.stringify(data.user));
You can refer to following article for more context on the above methods;
https://vkglobal.hashnode.dev/js-clone-object
OR
const savedUser = ._cloneDeep(data.user); // to use this you need to import external loadash library.
Solution 2:[2]
I may misunderstand the question, but should this:
gOnInit(): void {
this.user = this.formatUser(this.user);
}
be this:
ngOnInit(): void {
this.savedUser = this.formatUser(this.user);
}
Solution 3:[3]
This happens because the reference is the same for both the user & savedUser variable. You can fix this by creating a copy in the constructor of the object:
this.user = data.user;
this.savedUser = Object.assign({}, this.user)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Vishwak |
| Solution 2 | DanielG |
| Solution 3 | Bodhi |
