When utilizing localForage to store data offline, I encountered an issue with generating unique key values for each form submission. My goal is to have the key value generated dynamically as 'activity_1', 'activity_2', 'activity_3', and so on, every time a new form is submitted.
Below is the code snippet in question:
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);
});
});
For visualization, you can access the complete code on this CodePen link.
The problem arises when the key 'activity_1' is consistently generated for each form submission, leading to overwrite of previous values stored at 'activity_1'.
To observe this behavior firsthand, try submitting the form multiple times and monitor your developer console for results.
I am seeking assistance on how to generate distinct keys for each form submission going forward.