I'm using localForage to store data offline. While adding key-value to store with setItem method, i want to generate the value of key like activity_1, activity_2, activity_3, etc, and this are generated when i submit the form. So for every form that i submit it should generate the key value differently.
Here is the code for that:
var getActivity = document.getElementById('getActivity'),
fetchVal = document.getElementById('fetchVal'),
log_form = document.getElementById('log_form');
function activityArr() {
var i = 1;
if(i > 0){
var keyVal = 'activity_' + i;
}
i++;
return keyVal;
}
log_form.addEventListener('submit', function(e){
e.preventDefault();
localforage.setItem(activityArr(), getActivity.value)
.then(function (val) {
console.log(val);
}).catch(function(err){
console.log(err);
});
localforage.keys().then(function(keys) {
console.log(keys);
}).catch(function(err) {
console.log(err);
});
});
Here's the codepen link for reference.
But in my case it generates key 'activity_1' for every form that i submit. So it overrides the previous value that is stored at 'activity_1'.
Just try to submit the form 2-3 times, and open your developer console to see the result.
How do i generate keys differently whenever i submit the form.
Don't make the i variable local. Every time the function is called, the i variable is reset to 1.
var i = 1;
function activityArr() {
if(i > 0){
var keyVal = 'activity_' + i;
}
i++;
return keyVal;
}