How to save data?

var data = {

'Harold' : {

    'Class' : '11',

    'Score' : '89%'

},

'Hadley' : {

    'Class' : '8',

    'Score' : '94%'

}

};

function updateData() {

var name = document.getElementById('name').value;

var clas =  document.getElementById('class').value;

var score = document.getElementById('score').value;

if(name === 'Harold') {

    alert('Student already exists');

    document.getElementById('demo').innerHTML = data['Harold']['Class'];

    document.getElementById('demo2').innerHTML = data['Harold']['Score']

} else if(name === 'Hadley'){

    alert('Student already exists');

    document.getElementById('demo').innerHTML = data['Hadley']['Class'];

    document.getElementById('demo2').innerHTML = data['Hadley']['Score'];

} else {

    if(clas !== '') {

        if(score !== '') {

            data[name] = {'Class' : clas, 'Score' : score };

        }

        alert('Student added to data')

    }

}

}

function retrieveData() {

var student = document.getElementById('newstudent').value;

if(student in data) {

    console.log(data[student]);

} else {

    console.log('Artist not available.Please add it.')

}

}

I have created a small page that adds data of a student( class and score ) and displays it below when searched.
The details added are added to the variable ‘data’ which is an object.
The problem is when i reload the page the saved data is lost.
How can I save data without losing it after I reload the page??

@DrJellyBean hey,

to have your data be persistent you need to either use local storage to save it to the browser or have database of some kind, storing to a variable, array or object alone only saves the data in memory which is lost on a reload.

2 Likes

So how do u write the code to save the data in local storage??

@DrJellyBean hey,

to save the data to local storage you use localStorage.setItem() the first argument is the name that you want to store it as and the second is the actual data which is best to stringify.

localStorage.setItem('myData', JSON.stringify(data));

then when you first start the page on a refresh you should retrieve the data with localStorage.getItem()

const myData = localStorage.getItem('myData');

then you can set it to the data object like so…

const data = myData ? JSON.parse(myData) : {

'Harold' : {

    'Class' : '11',

    'Score' : '89%'

},

'Hadley' : {

    'Class' : '8',

    'Score' : '94%'

}
};

to clear the storage use localStorage.clear()