Create the key's value in a dynamic manner within localforage

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.

Answer №1

It is important to avoid making the i variable local, as it will reset to 1 every time the function is called.

var i = 1;
function activityArr() {
  if(i > 0){
    var keyVal = 'activity_' + i;
  }
  i++;
  return keyVal;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to manage your javascript variables

Here is the code snippet I am working with: var json = jQuery.parseJSON(data); console.log(json) When I run this code, the output looks like this: Object {sql: "SELECT venta.cliente_tipodoc,count(*) AS cantidad FROM venta venta", results: Array[1], ...

The image slide change feature ceases to function properly when incorporating two separate functions

I have a function that successfully changes the image of a container every 5 seconds. However, I am facing an issue when trying to add 2 containers side by side and change their images simultaneously. When I run the functions for both containers, only one ...

What could be causing the issue of images not loading in Chrome while they are loading perfectly in Mozilla when using CSS3?

Recently, I dove into a project utilizing react with webpack, and everything was smooth sailing until I encountered the CSS hurdle. Despite successfully configuring webpack, trouble brewed when it came to styling. Specifically, setting the background image ...

What causes unescaped HTML characters to become unescaped when using $('div :not(script)').contents().filter(function()?

Developing a Chrome Extension that utilizes a click-to-call API, I have encountered an issue where certain pages are displaying unusual behavior. After investigating, I have identified this specific code snippet as the source of the problem. var rxpCtc = n ...

Looking to scan through a directory of .html files in Node.js to find specific element attributes?

Imagine trying to tackle this task - it's like reaching for a needle in a haystack. Picture a folder containing a static website, complete with images, stylesheets, and HTML files. My Node application needs to dive into this folder and extract only th ...

Are XHR2 credential requests truly secure or easily faked?

I am working to determine the level of security provided by credentialed XHR2 requests. More precisely, can I verify that the request originated from a browser runtime environment, and not from a bot (such as a server-side program) that might be able to m ...

Can you explain the significance of the colon in this context?

Upon reviewing some SearchKit code snippets (composed with react/jsx and es2015), I came across the following line in a jsx file: const source:any = _.extend({}, result._source, result.highlight) I am curious about the purpose or significance of the colo ...

Issue with long text in a resizable table using jQuery tablesorter 2.31.1

My issue is that when I try to resize the columns in tablesorter, they snap back into place. The column width set with resizable_widths does not apply correctly until a column is manually resized. Despite setting the width of all cells to 120px, any cells ...

Troubleshooting: Issue with Nested jQuery UI Accordion Implementation

I am having issues with the menu collapsing incorrectly. While the top level functions properly, the sub menus do not collapse as expected. I am unsure about the correct approach to fix this problem. Can anyone provide guidance? jquery $(function() { ...

The function `createUser` is currently not functioning properly on Firebase/Auth with Next.js

I am currently working on implementing email and password authentication using Firebase Auth with Next.js. This time, I want to utilize a dedicated UID for authentication purposes. In order to achieve this, I believe it would be better to use the createU ...

Tips for resolving the issue of receiving a warning about passing "onClick" to a "<Link>" component with an `href` of `#` while having "legacyBehavior" enabled in Next.js

My current project is displaying a lot of warnings in the browser console and I'm unsure about the reasons behind it. The warnings include: "onClick" was passed to with href of /discovery/edit but "legacyBehavior" was set. The l ...

What is causing the presence of NaN?

Initially: https://i.stack.imgur.com/2n1Zk.png After Interaction: https://i.stack.imgur.com/Of0pO.png $(document).ready(function () { var output = document.getElementById("whole"); if (!navigator.geolocation) { ...

When utilizing the withStyles HOC, innerRef is not included in the passing of other props when passed through React.forwardRef

I have encountered a problem while passing the ref using React.forwardRef to the down component. This method usually works fine. <SomeComponent component={React.forwardRef((props, ref) => <MyComponent innerRef={ref} {...props} />)} .../> Ho ...

Ways to implement a fixed navigation bar beneath the primary navbar using ReactJS

Utilizing ReactJS, I am endeavoring to create a secondary (smaller) navbar in the same style as Airtable's product page. My primary navbar is situated at the top and transitions from transparent to dark when scrolled. The secondary bar (highlighted in ...

Trading keys between arrays in JavaScript

I have a set of simple objects contained within an array: var myObject1 = [ {name: "value1", adddress: "545454545445"}, {name: "value2", adddress: "323233223"}, {name: "value3", adddress: "332 ...

JavaScript effectively divides multiple child dropdowns with the main dropdown, thanks to Bootstrap innovation

I have implemented a jQuery function to dynamically change multiple child dropdowns based on the selected value of the main dropdown. For reference, you can view the image here. However, I encountered an issue when applying the Bootstrap styles "form-con ...

Utilizing Socket IO and Node JS to stream audio from a microphone via sockets

I am currently developing an app that requires users to use their phone's microphone to communicate with each other in the game lobby. However, I have encountered several challenges along the way. My approach involves using Node JS socket io and sock ...

Leveraging Angular-translate with state parameters

My current challenge involves using angular-translate for localization. Everything is working smoothly except for translating data within state parameters. As an example, consider a state configuration like this: .state('about', { url: "/ ...

Sorting and selecting isotopes, with the option to filter or unfilter

All day I've been struggling to find a solution for my isotope filtering issue. I'm using classes from the database to tag items, such as categories and dates, and allowing users to filter them. The tricky part is making these filters work like o ...

using flexbox in react does not automatically resize

I am attempting to create a layout where the screen is split into two sections - one green block taking up 1/4 of the screen and one yellow block taking up 3/4 of the screen using react.js. However, when I tried implementing the code below, both blocks end ...