Difficulty with local storage overwriting

I've been developing a quiz app using only JavaScript. The app allows users to choose a username, answer questions to increase their score, and saves the data in variables. When the game ends, a message is displayed along with the top 5 scores achieved by users. To store this information, I am utilizing local storage. However, I encountered an issue where the data is being overwritten when the game is restarted or played again. For instance, the first user's name gets replaced by the newer player. Here is the code snippet for saving the data:

var obj = convertUserAndScore(user, score);
var players = new Array;

players.sort(function(a, b){
return a.score - b.score;
});


players.push(JSON.stringify(obj));

localStorage.setItem("players", players);


function convertUserAndScore(user, score) {

return { "username": user , "score": score};
}

Answer №1

There are a few issues here.

First, you are always initializing an empty array and not retrieving any stored data from localStorage.

Additionally, you are immediately storing this empty array in localStorage, which could potentially overwrite any previously stored arrays.

Thirdly, you are stringifying the elements in the array instead of the entire array itself.


Let's walk through what should be done during page load:

var localData = localStorage.getItem("players");
// Check if there is stored data or use an empty array
var players = localData ? JSON.parse(localData) : [];

When making changes to the array, remember to stringify the entire array:

var someObj = //...
players.push(someObj);
localStorage.setItem("players", JSON.stringify(players));

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

Show the initial three divs first before implementing a toggle for the rest

My dashboard consists of multiple panels, each containing various items. Some panels have a large number of items. I am looking to display only the first three items in each panel and provide a toggle option to show/hide the rest. <div class="dashboa ...

Encountering a window error while utilizing emoji-mart in a Next.js application

Thinking of incorporating the emoji-mart package into my upcoming Next.js application. I'm encountering an error while running it on localhost: ReferenceError: window is not defined file:///C:/Users/../node_modules/emoji-mart/dist/main.js (1667:47) ...

Is it possible to use export default Enum in TypeScript?

I am facing an issue with exporting an enum object as default at the top level in my code. Here is what I tried: export default enum Hashes{ FOO = 'foo', BAR = 'bar', } However, this resulted in an error message: Module parse failed ...

Creating gulp tasks that are compatible across different platforms, particularly using gulp-shell

I'm currently facing an issue with running gulp tasks on Windows. The shell commands that work perfectly fine on Linux are not recognizing environment variables using the $var syntax (equivalent to %var% in Windows). Do I need to create a separate gul ...

Express JS: The requested resource does not have the 'Access-Control-Allow-Origin' header

Currently, I am encountering an issue with my API running on a server and the front-end client attempting to retrieve data from it. Previously, I successfully resolved the cross-domain problem, but now it seems like something has changed as I am receiving ...

Guide to Generating Extern for a Constant Variable in Google Closure Compiler (Variable Cannot be Renamed due to Eval)

Currently, I am using Google Closure Compiler in "SIMPLE_OPTIMIZATIONS" mode for my JavaScript code. However, I encountered an issue when the obfuscation changed the variable name from "_u" to "a", resulting in an error that "_u" is not defined in the cons ...

Calculating the size of an array based on its attributes

Hey there, I'm working with an array containing attributes and need to determine its length. In this particular case, the array should have a length of 2 since there are only two "items" present. {"items":[{"value":"2","valor":0,"name":"Limpeza"}, {" ...

What is the best way to manage files in Vue.js?

I am faced with a challenge in storing image files and video files as Blob data. One thing I like is that the uploaded video and image files display instantly, which is pretty cool. I'm not entirely sure if the code below is correct - how can I navi ...

Event Listener for Spelling Quiz Buttons: Check Correct and Incorrect Answers

I am currently in the process of developing a spelling quiz for a project website using HTML, CSS, and JavaScript. The idea is to present the user with a word that has two missing letters indicated by underscores. The user then selects the correct answer ...

What are the best scenarios for utilizing (a)synchronous calls?

Currently, I am working on a project for my office as a learning exercise. We have a tradition of bringing food every Monday, so I decided to create a program that displays each person's turn. My webpage can generate a calendar with a spare color colu ...

Error: Unforeseen token encountered while attempting to import React in Javascript

Upon executing the command 'npm run start', I encountered this error: import React from 'react'; ^^^^^ SyntaxError: Unexpected identifier at Module._compile (internal/modules/cjs/loader.js:721:23) at Object.Module._exten ...

Achieving port forwarding in Node.js with a proxy server: a comprehensive guide

I am currently working on a Node.js project where I need to set up a proxy server to forward requests from one port to another. The code I found online is not working properly, so I may be doing something wrong. I would appreciate any help in providing a w ...

An ajax call triggers a 500 error response when initiated within another ajax call

I am encountering an issue with my Ajax requests. There are two requests - one (referred to as Ajax#1) sends data to the backend, and the other (Ajax#2) uses that data to load content onto the front end. To ensure that Ajax#2 runs after Ajax#1, I attempt ...

The JSON primitive is not valid in the conversion process:

While attempting to execute a script that retrieves a JSON file from a CMS endpoint and passes it through the pipeline to be converted using convertfrom-json, an error occurred with the message "Invalid JSON primitive." ConvertFrom-Json : Invalid JSON p ...

The issue with Nextjs getStaticPaths is that it is not retrieving data from Firebase Firestore

I'm encountering an issue with fetching dynamic data from firestore in nextjs using getStaticPaths. While rendering the data from firestore with getStaticProps works, I'm facing a problem when trying to access specific item details as it leads me ...

What is preventing me from making a call to localhost:5000 from localhost:3000 using axios in React?

I have a React application running on localhost:3000. Within this app, I am making a GET request using axios to http://localhost:5000/fblogin. const Login = () => { const options = { method: "GET", url: "http://localhost:5000/fblogin", ...

React filtering displaying array elements that appear single time

I've been working on this React code to filter and search items based on user input. The issue I'm facing is that when I delete the text input and try again, the filtered items disappear and don't show up unless I reload the page. I'm c ...

Utilizing React-Redux along with Redux-Thunk in a functional component to dynamically modify the UI upon receiving data from an external API

Within my functional component, I am utilizing a custom hook to fetch data from an API using Redux. const useFetching = (someFetchActionCreator) => { const dispatch = useDispatch(); useEffect(() => { dispatch(someFetchActionCreator() ...

Adjust CardMedia Images to match their content in the new MUI 5 version

I’m looking to have my images fully fill the CardMedia component. However, because they are of varying sizes, some end up being cropped like this: https://i.stack.imgur.com/JHIrT.png Additionally, when resizing the images, some get cut off as well: ht ...

Hide the div element when the url contains the word 'word'

I did some research online, but I couldn't find any information on whether this is doable. I'm currently using IPBoard and after their latest IPS4 update, I'm facing an issue where I can't simply change the homepage anymore. Now, I have ...