Reputation: 141
everyone,
I have a problem with localStorage and I don't know how to fix it. I have a form that is asking first for name and gender and on step 2 I have another form that is asking for weight and height. My data from step 1 is saved in localStorage but when I try to add the values from step 2 they just replace in localStorage with the step2 information instead of adding with the information from step 1. What can I do to fix it, if someone has time and can help I would appreciate a lot.
Regards,
TS. from step 1, this is how I store the step 1 form and its working.
submit() {
localStorage.setItem('quizData', JSON.stringify(this.form.value));
console.log(JSON.stringify(this.form.value));
}
This is TS from step2 and its not working, I tried to push the values in the step 2 form but its just replacing the values in localStorage instead of adding them in the same key quizData.
submit() {
let test = JSON.parse(localStorage.getItem('quizData') || '{}');
let updated = test.push(this.form.value);
localStorage.setItem('quizData', JSON.stringify(updated));
console.log(test);
}
What can I do to be able do add both data from step 1 and step 2 instead of replacing the data. Thanks a lot for your time.
Upvotes: 0
Views: 569
Reputation: 55333
Try this
let test = JSON.parse(localStorage.getItem('quizData') || '{}');
let updated = { ...test, this.form.value };
Documentation: Spread in object literals
Upvotes: 4