Problem with localstorage after pagerefesh. Array is empty

Viewed 85

Okay, so I'm lost here. I've tried all (or so it seems). I'm brand new to javascript and I'm trying to save inputdata into an array and then to localstorage. It works fine until I refresh the page, then the array is empty and the data is lost.

Can someone help?

Here's my code. Very simpel actually.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
<input id="input-id-first-name" value="Frontname">
<button id="btn">Send value</button>
<p id="output"></p>

</body>
<script>
    const inputFirstNameEl = document.querySelector("#input-id-first-name");
    const btnEl = document.querySelector("#btn");
    const outputEl = document.querySelector("#output");

    
    const array = []
    
    let getStorage = JSON.parse(localStorage.getItem("storage"))
    btnEl.addEventListener("click", getInput);
    
    function getInput () {
        localStorage.setItem("storage", JSON.stringify(array));
        const getInputFirst = inputFirstNameEl.value;
        array.push(getInputFirst);  
        
    }
    
    console.log(JSON.parse(localStorage.getItem("storage")));

</script>
</html>

1 Answers

The problem, that there is data in your localStorage and after a page refresh it's lost, can't be reproduced at my machine.

But maybe this is a part of the problem:

const array = []
...
function getInput () {
   localStorage.setItem("storage", JSON.stringify(array)) // write current content of array to localStorage
   const getInputFirst = inputFirstNameEl.value
   array.push(getInputFirst) // add input of textfield to array
}

So you're writing the content of the empty array to localStorage and afterwards adding the content of the textfield to your array.

Put the localStorage.setItem("storage", JSON.stringify(array)) at the end of your function.

As another hint, use the DevTools (F12) of your browser. At the example of Chrome, in the tab "Application" you can see what's actually in your localStorage. Maybe it's better then only console.log.

Related