leveraging the localStorage feature in a for-in iteration

I am new to stackOverflow, although I have browsed the forums for help in the past. However, this time I couldn't find a solution to my current issue, so I decided to create an account and seek assistance.

The problem at hand is related to a workout application that consists of 3 pages - page 1: where the user selects gym equipment (bike, rower or x trainer) and difficulty level, page 2: displays specific workouts based on the selections, and page 3: the actual workout to be completed.

My goal is to store certain data in a localStorage object depending on the link clicked by the user. But, each time a link is clicked, only the last value in the 'for in' loop gets stored, regardless of the link. Here's a simplified explanation:

PAGE 1: User selects equipment and difficulty from dropdown menus

// Constructor function to create workout instances
function Workout(name, desc, loc, work_rest, res, intensity){
    // ... properties defined here
}

// Create Workouts for bike
var bike = {
    easy: [
        {workout_1: new Workout('Tabata', 'This is a tabata style workout', '../Workout_page_example/index.html', [20, 10,...])},
        {workout_2: new Workout('Classic_HIIT', 'This is a HIIT session', '../Workout_page_example/index.html',[60,30,...])},
        {workout_3: new Workout('Clock_Face', 'Beat the clock', '../Workout_page_example/index.html',[120, 60...])}
    ],
    int:[],
    adv:[]
};

btn.addEventListener('click', function() {
    if(equipment.value === "bike"){
        if(difficulty.value === "easy"){
            localStorage.setItem('get_info', JSON.stringify(bike.easy));
        } else if(difficulty.value === "int"){
            localStorage.setItem('get_info', JSON.stringify(bike.int));
        } else if(difficulty.value === "adv"){
            localStorage.setItem('get_info', JSON.stringify(bike.adv));
        }
        location.href = 'workouts/index.html';
});

This above page is working fine. Now, moving on to Page 2 which displays all available workouts based on the user's previous selections:

PAGE 2: Display workouts based on equipment and difficulty selected

window.addEventListener('load', function(){
    var getInfo = JSON.parse(localStorage.getItem('get_info'));
    var dom = document.getElementById('section');

    for(var key in getInfo){
        var obj = getInfo[key];
        
        for(var prop in obj){
            // display workout details
            dom.innerHTML += "<hr/><div class='workout_title'><h1>"+obj[prop].name.replace('_',' ')+"</h1></div>";
            dom.innerHTML += "<div class='workout_desc'><h4>"+obj[prop].desc+"</h4></div>";

            // store data in localStorage
            localStorage.setItem('work_rest', JSON.stringify(obj[prop].work_rest));
            localStorage.setItem('resistance', JSON.stringify(obj[prop].res));
            localStorage.setItem('intensity', JSON.stringify(obj[prop].intensity));

            dom.innerHTML += "<div class='workout_link'><a href='"+ obj[prop].loc +"' id='"+obj[prop].name+"'>START >></a></div>";
        }

    }

})

On clicking the links, only the data for the 'Clock Face' instance is being stored in the localStorage object. I understand why this is happening but unsure how to fix it.

Answer №1

There is a flaw in your current approach where you are cycling through the 3 workouts and saving them without giving the user a chance to choose a workout. This causes the stored workout data to be constantly overwritten in each iteration, resulting in only the final workout being saved in the array. This means that all previous workouts have been replaced, creating a chain of overwriting that leads to only one workout being stored effectively.

Answer №2

I managed to solve the issue:

 window.addEventListener('load', function(){

    var getInfo = JSON.parse(localStorage.getItem('get_info'));
    var dom = document.getElementById('section');

    var names=[]; //initialize names array
    var workRestArr = [];
    var resArr = [];
    var intArr = [];


    for(var key in getInfo){
        var obj = getInfo[key];


        for(var prop in obj){

            dom.innerHTML += "<hr/><div class ='workout_title'> <h1>"+obj[prop].name.replace('_',' ')+"</h1></div>"; //replace underscore with space in workout names with more than one word - display name
            dom.innerHTML += "<div class='workout_desc'><h4>"+obj[prop].desc+"</h4></div>"; //display description

            dom.innerHTML += "<div class='workout_link'><a id='"+obj[prop].name+"'>START >></a></div>";


            names.push(obj[prop].name); //store all ids in names array
            workRestArr.push(obj[prop].work_rest); //store all work_rest in array
            resArr.push(obj[prop].res); // store all resistance levels in array
            intArr.push(obj[prop].intensity); //store all intensity levels in an array

        }

    }


    for(var i = 0; i<names.length; i++){
        var el = document.getElementById(names[i]);
        var w = workRestArr[i];
        var r = resArr[i];
        var int = intArr[i];

        (function(w, r, int) {
            el.addEventListener('click', function() {
                localStorage.setItem('work_rest', JSON.stringify(w));
                localStorage.setItem('resistance', JSON.stringify(r));
                localStorage.setItem('intensity', JSON.stringify(int));
                location.href = '../Workout_Page_example/index.html';
            })
        })(w, r, int);

    }

})

Although I am still unsure of the intricate workings of this code, my assumption is that it involves closures and variable scope. It would be beneficial to have a detailed explanation. Thank you

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

Sending data from jQuery to an AngularJS function is a common task that can be accomplished in

In my Controller, I have a function that saves the ID of an SVG path into an array when a specific part of the image.svg is clicked. $(document).ready(function(){ var arrayCuerpo=[]; $('.SaveBody').on("click", function() { ...

Is it considered acceptable in React for the value of one state to be determined by another state?

Consider this scenario: state1 tracks the mouseover of clientX and clientY, while state2 retrieves the value from state1 upon clicking. Is this implementation acceptable? const [move,setMove]=useState([]) const [click,setClick]=useState([]) useEffect(() ...

What could be causing my function to execute thrice?

I cannot seem to figure out why my tag cloud is causing the required function to run multiple times instead of just once when I click on a tag. This issue persists whether using jQuery or plain JavaScript. What am I missing? The code I have is very simple, ...

Utilize AJAX to invoke a PHP function through JavaScript

I am trying to call a PHP function from Javascript without using jQuery. The PHP function I want to call is: <?php function helloworld() { echo 'Hello Ashish Srivastava'; } ?> It is located in the hello.php file. My Javascript code ...

Ensure the left and right screen widgets remain fixed in their positions as the user scrolls down the page using the spacebar

Currently, I have a webpage that showcases products with a large height attribute. I am looking for a way to make the page scroll down when the user hits the space bar to view more products. However, I want my screen widgets such as the shopping cart and ...

What are the steps to lift non-React statics using TypeScript and styled-components?

In my code, I have defined three static properties (Header, Body, and Footer) for a Dialog component. However, when I wrap the Dialog component in styled-components, TypeScript throws an error. The error message states: Property 'Header' does no ...

Simple solution for storing key-value pairs temporarily in a form using JQuery

Is there an elegant method to temporarily store an array of string values in a form? In my article editing form, users can add tags as string values. I don't want these tags to be persisted until the user saves the entire article, so I require a way ...

What is the process for changing CORS origins while the NodeJS server is active?

Currently, I am in the process of modifying the CORS origins while the NodeJS server is operational. My main goal is to replace the existing CORS configuration when a specific user action triggers an update. In my attempt to achieve this, I experimented w ...

The issue of JavaScript failing to connect to the HTML file

As I work on my basic HTML file to learn Javascript, I believed that the script was correctly written and placed. Nevertheless, upon loading the file in a browser, none of the script seems to be functioning. All of my javascript code is external. The follo ...

JavaScript does not function properly on dynamically loaded content from AJAX requests and it is not relying on

I am currently using ajax to load all content from 'mysite/math/' into math.php. I want to render the loaded math content using katex. KaTeX GitHub Inside math.php, I include the Katex library from the CDN mentioned in the link above. The HTML ...

Is it possible for me to move props object deconstruction into a separate module?

Here is my scenario: I have two React components that share 90% of the same props data, but display different HTML structures. I would like to avoid duplicating variable declarations in both component files. Is there a way to extract the common props des ...

As the height is expanded, the background color gradually infiltrates the body of the page

I am currently working on an angular application that utilizes angular-pdf. The controller and view function perfectly, and the PDF is displayed correctly, except for one issue. The height of the PDF exceeds the min-height of the module, causing it to expa ...

Issue with dropdown component in material ui version v1.0 beta 26 encountered

Currently, I am encountering an issue with the dropdown component while using Material UI v1.0 beta.26. In this updated version, you are required to utilize the Select component along with MenuItem. Although my dropdown is successfully populated upon rend ...

The application monitored by nodemon has halted - awaiting modifications in files before restarting the process

1. My ProductController Implementation: const Product = require('../models/product') //Creating a new product => /ap1/v1/product/new exports.newProduct = async(req, res, next) => { const product = await Product.create(req.body); re ...

Tips for incorporating an anchor tag within an img tag in HTML?

Is it possible to add an anchor tag inside an img tag in HTML? <img src="img.jpg" alt="no img" /> I want to include the following inside the img tag: <a onclick="retake();" > Retake </a> The goal is to allow users to retake a photo by ...

Tips for updating the content of a div with fresh data using a slideshow effect in jQuery

Imagine you have a div called A and an array filled with text data. When t=0, div A will display $data[0]. Then, after every n seconds, I want the div to show the next piece of data in the array. I am interested in creating a transition effect similar to ...

Prevent repetitive content on your Node.js server

After realizing my small image hosting has many duplicate content, I am looking for a solution to prevent this issue in the future. My idea is to use either checksum or hash code so that whenever a new file is uploaded, it will be hashed and compared with ...

Generate a custom website using React to display multiple copies of a single item dynamically

As a newcomer to React and web development, I've been pondering the possibility of creating dynamic webpages. Let's say I have a .json file containing information about various soccer leagues, structured like this: "api": { "results": 1376, ...

Identifying text within a paragraph using JavaScript regex, excluding any URLs mentioned

How can I use JavaScript on the client side to find a search term in a paragraph while excluding any matches that are part of a URL? I attempted to use the following regex but encountered an error: "A quantifier inside a lookbehind makes it non-fixed widt ...

Learn the process of transmitting data from middleware to components and APIs in Next.js version 13

I've been experimenting with the Next Js 13 middleware feature and I'm a bit confused about how to pass data from the middleware to components/pages/api. For example, when trying to pass payload data or determine who the currently logged-in user ...