Home > Back-end >  how do i add new obj in an array in localStorage everytime I submit my form
how do i add new obj in an array in localStorage everytime I submit my form

Time:08-19

how do i add new obj in an array in localStorage in ReactJS everytime I submit my form?

the issue is ,it is updating everytime in hit sumbit ,i want results to [{1},{2},...]

CodePudding user response:

When u want to save variable to local storage :

localStorage.setItem("test",JSON.stringify([{username:"John",password:"123"}]))

Then :

  const lclStrg= JSON.parse(localStorage.getItem("form"))
  lclStrg.push({username:"Mohammad",password:"321"})
  localStorage.setItem('form',JSON.stringify(lclStrg))

So when u save the form the code should be as following : let formInfo={ username:"micheal", password:"123456" } if(lclStrg.getItem("form")){ const lclStrg= JSON.parse(localStorage.getItem("form")) lclStrg.push(formInfo) localStorage.setItem('form',JSON.stringify(lclStrg)) } else{ localStorage.setItem("form",JSON.stringiy([formInfo]) }

  //formInfo is the value submitted by the form 

CodePudding user response:

You can try out this code: I have printed the values before adding a new item and after adding a new item to the localStorage

let data = localStorage.getItem("form_data")

console.log(data)

let formdata = {
  "name": "Nidhey",
  "email": "[email protected]",
  "phone": "11111111"
}

if(data == null){
  data = []
  data.push(formdata)
  localStorage.setItem("form_data", JSON.stringify([formdata]))
}else{
  data = JSON.parse(data)
  data.push({
     "name": "John",
    "email": "[email protected]",
    "phone": "11111111"
  })
  localStorage.setItem("form_data", JSON.stringify(data))
}

console.log(data)

Output:

[
    {
        "name": "Nidhey",
        "email": "[email protected]",
        "phone": "11111111"
    },
    {
        "name": "John",
        "email": "[email protected]",
        "phone": "11111111"
    },
    {
        "name": "John",
        "email": "[email protected]",
        "phone": "11111111"
    }
]
  • Related