Search code examples
javascriptreactjsreactstrap

How can I append user inputs in a single array on localStorage key in reactjs?


Every time a new input is entered, I am trying to make it so that input is appended into an array in localstorage. I am currently using localStorage.setItem('Inputs', JSON.stringify(document.getElementById("inputVal").value)) which takes the value but does not add it to any array and instead replaces the previous value. How would I go abouts adding the input into an array for localstorage? I am also wondering if I could use .appendChild()?

quick update: I have also tried

var valueS = document.getElementById("inputVal").value;
    const arr = [];
    const newArry = [
      ...arr,
      valueS
    ]
    //arr.push(valueS)
    localStorage.setItem('Data', JSON.stringify(newArry))

Solution

  • Just like @nIta, @Patrick Evans and @David Grosh pointed out, the const arr = [] should contain the localstorage array.

    The solution that works for me is as follows:

    var valueS = document.getElementById("inputVal").value;
        const arr = [JSON.parse(localStorage.getItem('Data'))];
        const newArry = [
          ...arr,
          valueS
        ]
        localStorage.setItem('Data', JSON.stringify(newArry))