Ensuring that localStorage objects continue to iterate when clear() is called within the same function

When a user completes the game loop or starts a new game, I want to clear all local storage while still keeping certain values intact.

Currently, I am able to do this for sound volume values:

// code inside a conditional statement triggered when starting a new game
if (newGameBool === '1') {
    var tst = myAu;
// myAu is the stored sound value set by the user using an input range

    localStorage.clear();

    localStorage.setItem("Au", tst); // After clearing local storage, set the same value again 

    UI.myLoad(); // Reload function that interacts with local storage

}

How can I achieve the same for keys with iterating numbers attached to them?

Here is how I save these keys:

var i = +v + +1; 

localStorage.setItem("v", i);

var vv = localStorage.getItem("v");

localStorage.setItem("LdrBrd_" + vv, JSON.stringify(LdrBrd)); // Saves data with iterating key names

Implementing retrieval similar to the sound function:

var gv = v + 1; // Retrieve the value from local storage and adjust for off-by-one error. gv is a local variable.
if (newGameBool === '1') {
    var ldd, vg;

    for (var ii = 0; ii < gv; ii++) {
        var ld = localStorage.getItem("LdrBrd_" + ii);
        if (ld != null) {
        // Values to retain beyond the clearing point
            ldd = JSON.parse(ld); // Parse saved JSON string data
            vg = ii; // Number of values retrieved
        }

    }

    localStorage.clear();

    for (var xx = 0; xx < vg; xx++) {
        var nld = localStorage.getItem("LdrBrd_" + xx);
        if (nld != null) {
           localStorage.setItem("LdrBrd_" + ii, JSON.stringify(ldd));
        }
    }
    localStorage.setItem("v", vg);

    UI.myLoad();

}

I have been using console.log() at different points to monitor the process. I commented out the clear function just to check if the values were incorrect, but they did not save at all. I attempted to create a fiddle, but local storage was not functioning there. In Visual Studio, everything works fine, but the script for this file is nearly 2000 lines long, so I tried to organize it as best as I could.

Thank you in advance for any assistance or advice.

Answer №1

After spending several days stuck on this issue, I believe I have found a solution that works. In the spirit of posterity, I will provide an answer to my own question.

localStorage.clear();
/*  ^LS clear() function is above all new setItem codes, some variables are declared globally and some are declared at the top of the functional scope or as param^  */
var itemClass = document.querySelectorAll(".itemClass");//the strings are here

if (itemClass) {//make sure some exist
    for (var p = 0; p < itemClass.length; p++) {//count them
        mdd = JSON.parse(itemClass[p].innerText);//parse the data for saving

        localStorage.setItem("v", v);//this is the LS item that saves the amount of items i have, it's declared at the top of the functions timeline.
        localStorage.setItem("LdrBrd_" + p, JSON.stringify(mdd));//this setItem function will repeat and increment with 'p' and assign the right string back to the key name it had before.
    }
}

The key approach is to link the strings directly to an element by calling the class name. I then ran a loop to count them. 'mdd' captures each desired item. Finally, the items are reset to their original state.

This method has enabled me to create a system for users to collect trophies, which persist even after clearing the localStorage when starting a new game.

I utilized CSS to hide the text from the string.

color:transparent;

In my gameLoop, there is a function that reads the saved strings and displays them as cards beneath the hidden strings.

Answer №2

To maintain certain values, I suggest following one of these two approaches:

  1. Avoid using localStorage.clear() and instead selectively remove the values you don't want by using

    localStorage.removeItem('itemName')
    . If your item names have a numeric aspect, consider implementing this in a loop to streamline the process.

  2. Prioritize saving the specific item(s) you want to keep before executing clear(), then restore them afterwards. This method is more suitable when there are significantly more items to be deleted than retained (refer below).

function mostlyClear() {
    var saveMe = {};
    saveMe['value1'] = localStorage.getItem('value1');
    saveMe['anotherValue'] = localStorage.getItem('anotherValue');
    localStorage.clear();
    for(var prop in saveMe) {
        if(!saveMe.hasOwnProperty(prop)) continue;

        localStorage.setItem(prop, saveMe[prop]);
    }
}

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

Ensure that the line above is shorter in length compared to the following line

Is there a way to ensure that the previous line of text is always shorter than the next one, even if the length of the text is unknown? For example: Lorem ipsum dolor sit amet, consectetur adipiscing et libero posuere pellentesque. Vivamus quis nulla jus ...

The leaflet_Ajax plugin is constantly searching for the default marker symbol located at js/images/marker-icon.png

Although I'm relatively new to Leaflet, I have experience creating interactive maps in the past. Recently, I've been working on a project involving displaying GPS data from a UAV. The UAV transmits location information to a server, which then ret ...

Is there a way to send JSON using ExpressJS in UTF-8 encoding?

Currently facing an issue with my new web app that I haven't encountered in the past. Experimenting with a simple code snippet like this: var jsonToSend = {hello: "woørld"}; app.get('/someUrl', function(req, res) { res.setHeader('Co ...

The controller function is not triggered if the user does not have administrator privileges

I have a code snippet in which my controller function is not being triggered for users who do not have the role of "Admin". Can someone help me identify where I went wrong? Just to clarify, the controller function works fine for users with the role of "Adm ...

How can I access a value stored within a JSON structure containing nested dictionaries?

I'm struggling to extract a value from a 2D JSON structure and display it in a TableView. I utilized AFNetworking for fetching the JSON data. The following code is created in Xcode 6 beta 7: func apiConnetion() { var result: NSArray = [] ...

Incorporating Entrance Animations for Individual Elements within ngView Using AngularJS

Can each content within ngView be animated individually upon entering, rather than the entire View (div) itself? ...

How to Customize the Navbar Position in Bootstrap 3 when the Brand/Logo is Collapsed

I am currently in the process of creating my first website and experimenting with the Bootstrap 3 framework. The navbar I have selected is designed to adjust based on screen size, collapsing into a small button for use on tablets and mobile devices. Howe ...

Establishing flow types and generating unchangeable records

Looking to integrate Flow with Immutable.js Records, I've set up my record like this: const MyRecord = new Immutable.Record({id: undefined}) Now when I create records using new MyRecord({id: 1}), Flow gives me an error: constructor call Construct ...

Here's a guide on executing both GET and POST requests using a single form

Currently, I am developing a web application which involves using a GET request to display checkboxes in a form. The selected data from the checkboxes needs to be sent back to the server using a POST request. However, I'm facing an issue with performi ...

What is the best way to remove table cells from a TableBody?

Currently, I am in the process of designing a table to display data retrieved from my backend server. To accomplish this, I have opted to utilize the Table component provided by Material UI. The data I retrieve may either be empty or contain an object. My ...

Converting a JSON to CSV for a substantial dataset - currently closed

In my possession is a .txt file filled with over a million JSON entities that were generated by a python program, each having different keys. Below is just a sample of what the file contains: { "category": "Athlete", "website": "example.com", ...

Issues with JSON data not functioning properly when using file system in JavaScript

When attempting to parse a JSON file, I encountered some errors. The file is located in a directory within my JavaScript file, under the 'fs' in a folder named "recipes." Within this folder, there are 3 JSON files, each representing a separate ob ...

The onClick event in React/NextJS is not functioning properly when applied to an external component

One dilemma I am facing involves my main page and a button component that I have created to be reused throughout my project. Strangely, when I add the onClick event to the external component, the click event does not seem to work. However, if I create the ...

Build a unique array of identifiers extracted from an object

I am seeking advice on how to extract an array of IDs values by iterating through an object in React JS. const initialState = useMemo(()=> { return dataTable.filter(result => favorites.some(favorite => result.id === favorite.id)) },[ ...

Access view name in controller using Ui-Router

Utilizing the ui-router in AngularJS allows for the implementation of multiple views within the same page/state. While each view consists of a template, controller, and more, there appears to be no straightforward method of assigning a "resolve" function ...

Attempting to grasp the fundamentals of angular Routing, however, upon attempting to reload the page, nothing appears to be displayed

While working in the Bracket editor, I created a file structure with various files located under the 'scripts' tags within the Index.html file. The root folder is named 'projectAngular', inside which there are subfolders like 'appC ...

Exploring the nested JSON field using a map function

Here is an example of JSON data: { "name": "John", "address": { "city": "New York" } } I am wondering how I can convert this JSON into the following DTO using Jackson: final class PersonDto { private final String name; // name private fina ...

How is the server architecture typically designed in a node.js application?

Currently, I am developing a node.js application using socket.io and I'm seeking advice on how to structure the folders properly. The files that I have in my project include: Server.js package.json Additionally, I have: Client.js Index.html Incl ...

"Unleashing the power of React Native: A single button that reveals three different names

I have a piece of code that changes the name of a button from (KEYWORD) to a different one (KEYNOS) each time it is clicked. How can I modify it to change to a third value (KEYCH), where the default name is (A, B, C... etc), the first click shows Numbers ...

Tips for customizing the appearance of a Link component while it is the active page in Next.js

I'm seeking advice on how to style an anchor component differently when it is active on a page. Here's the code I have so far: import Link from 'next/link'; import styled from 'styled-components'; const NavStyle = styled.nav` ...