Home > database >  store an object several times with different values on local storage javascript
store an object several times with different values on local storage javascript

Time:12-19

I'm just beginning on JS. Here is my code:

     score = {
        name: name,
        maxTurns: maxTurns,
        lowestProbability: lowestProbability * 100   '%',
        totalTurns: totalTurns,
        initialProbability: initialProbability,
        totalSuccess: totalSuccess,
        date: new Date().getTime() 
    }
   
    console.log(localStorage.getItem('score')); 
    
   
    let localData = localStorage.getItem('score')   JSON.stringify(score);
    localStorage.setItem("score", localData);

unfortunately, it doesn't work well, I don't know why.

Sometimes I get what I want: one line with the results per input, sometimes I have a huge quantity of data with wrong values. Is someone able to explain and help?

I tried to use push to add the data to the old results but it doesn't work with strings. Then I tried with but it doesn't work all the time.

CodePudding user response:

As far as I understand, you are going to save the scores from an API multiple times in the local storage and retrieve them back when you need them. For demo purposes, I have used string for the data values.

You can try this code:

score = {
  name: "name",
  maxTurns: "maxTurns",
  lowestProbability: "lowestProbability%",
  totalTurns: "totalTurns",
  initialProbability: "initialProbability",
  totalSuccess: "totalSuccess",
  date: "new Date().getTime() "
};

let localData;
let limit = 2; //Only adds the data 2 more times.

for (let index = 0; index <= limit; index  ) {
  index === 0
    ? (localData = { [index]: score })
    : (localData = Object.assign(JSON.parse(localStorage.getItem("score")), {
        [index]: score
      }));

  localStorage.setItem("score", JSON.stringify(localData));

  console.log(
    `LocalStorage  Iteration ${index}: `,
    JSON.parse(localStorage.getItem("score"))
  );
}

You can have a look at the demo here: https://codepen.io/dreambold/pen/vYaBwjq?editors=1010

CodePudding user response:

Basically you should set the item before retrieving it.

So before the console.log you should set the score in the localStorage:

window.localStorage.setItem("score", JSON.stringify(score));

Note that I used window.localStorage, to make sure that I am working on the localStorage.

After that, you can get the value from local storage, and set it again if you want as well.

I hope this helped you.

  • Related