0

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

3 Answers 3

2

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.
Sign up to request clarification or add additional context in comments.

Comments

0

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);
}

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.