Home > OS >  localStorage value doesn't automatically updated
localStorage value doesn't automatically updated

Time:07-25

<div >
                <h1>Your name...</h1>
                <input type="text" name="name" id="name" >
                <input type="button" name="button" id="button" value="Save">
</div>

I am new to localStorage, web storage in general. I made a very simple vanilla javascript project, "Say my name" app.

The project was about I input my name or anyone's name and when I clicked the "save" button, the name(input value) will be stored on localStorage.

I've tried setItem() feature and it worked, my input value was saved as localStorage value. But, when I typed new value and clicked the save button, the localStorage value didn't automatically updated. I had to refresh the localStorage every time I want to see the new value. Why is it like that?

Here is my simple code snippet:

const nameInput = document.querySelector('.name');
const btn = document.querySelector('#button');
const NAME_KEY = 'name';

const saveToLocalStorage = () => {
    localStorage.setItem(NAME_KEY, nameInput.value);
};

btn.addEventListener('click', saveToLocalStorage);
<div >
                <h1>Your name...</h1>
                <input type="text" name="name" id="name" >
                <input type="button" name="button" id="button" value="Save">
</div>

CodePudding user response:

const nameInput = document.querySelector('#name');
const btn = document.querySelector('#button');
const NAME_KEY = 'name';

const saveToLocalStorage = () => {
    localStorage.setItem(NAME_KEY, nameInput.value);
    document.querySelector('h1').innerHTML = localStorage.getItem(NAME_KEY);
};

btn.addEventListener('click', saveToLocalStorage);
<div >
                <h1>Your name...</h1>
                <input type="text" name="name" id="name" >
                <input type="button" name="button" id="button" value="Save">
</div>

CodePudding user response:

const nameInput = document.querySelector('.name');
const btn = document.querySelector('#button');
const NAME_KEY = 'name';

const saveToLocalStorage = () => {
    localStorage.setItem(NAME_KEY, nameInput.value);
};

btn.addEventListener('click', saveToLocalStorage);
<div >
                <h1>Your name...</h1>
                <input type="text" name="name" id="name" >
                <input type="button" name="button" id="button" value="Save">
</div>

C

  • Related