Home > OS >  How to store multiple form submissions as separate values in localStorage?
How to store multiple form submissions as separate values in localStorage?

Time:09-23

With this code, I am only able to store a single key/value pair in localStorage, and if the user enters a new value and submits the form it overrides the previous one. How can I store each form submission in localStorage?

import { Component, OnInit } from '@angular/core';
import { FormGroup,FormControl } from '@angular/forms';

@Component({    
  selector: 'app-registration',  
  templateUrl: './registration.component.html',
  styleUrls: ['./registration.component.css']
})
export class RegistrationComponent implements OnInit {
 
  myform!:any;

  constructor() { }

  ngOnInit(): void {
    this.myform = new FormGroup({
      username: new FormControl(''),
      email: new FormControl('')
    });
}

  onSubmit() {
    localStorage.setItem("formdata",JSON.stringify(this.myform.value));
  }

}

CodePudding user response:

What you are trying to do is to add an item in the array that you are using in the localstorage. Try getting first the data from the localstorage, add the item and sending it again. It will look like this:

onSubmit(){
      
      let arrayName = localStorage.getItem("formadata")
      arrayName.push(this.myform.value)
      localStorage.setItem("formdata",JSON.stringify(arrayName));
    
  }

CodePudding user response:

You are overwriting your previous localStorage entry with each onSubmit(), as you are giving the entry in localStorage the same "key" value.

A way to overcome this would be to give each localStorage entry that is saved in onSubmit() a unique identifer of some kind in it's "key" value.

One possible solution is to get the exact "time" in hours, minutes, seconds value (will be unique) and put that info in the "key" parameter of setItem().

This will generate a single, unique localStorage entry for every onSubmit() that is called.

Try something like this:

import { Component, OnInit } from '@angular/core';
import { FormGroup,FormControl } from '@angular/forms';

@Component({    
  selector: 'app-registration',  
  templateUrl: './registration.component.html',
  styleUrls: ['./registration.component.css']
})
export class RegistrationComponent implements OnInit {
 
  myform!:any;

  constructor() { }

  ngOnInit(): void {
    this.myform = new FormGroup({
      username: new FormControl(''),
      email: new FormControl('')
    });
  }

  onSubmit() {
    // Generate Unique Identifier using Hours, Minutes, Seconds of submittal
    const today = new Date();
    const uniqueTimeEntry = today.getHours()   ":"   today.getMinutes()   ":"   today.getSeconds();
    localStorage.setItem("formdata-"   uniqueTimeEntry, JSON.stringify(this.myform.value));
  }

}

If you are instead NOT trying to create individual localStorage entries for each form submittal, you could simply add the subsequent form submittals to the existing localStorage, without overwriting it:

onSubmit() {
  // Get localStorage by key, then append the new data.
  let prevEntries = localStorage.getItem("formdata");
  prevEntries.push(this.myform.value);
  localStorage.setItem("formdata", JSON.stringify(prevEntries));
}
  • Related