rob.m
rob.m

Reputation: 10591

How to add and remove items in localStorage?

I am trying to build a logic where we click a button and save an ID in localStorage. We could have 2 ids max. However, we can also remove an ID from it and add a new one. Finally, we cannot add more than 2 and these ids must be unique. These IDs will be then set as an input value in a form.

So I have four steps page:

Each page has:

<form id="post_form_id" method="post" action="/test/compare/"> 
   <input id="input_post_id" type="hidden" name="varPostId" value=""> 
   <button type="submit" class="btn btn-link nav-link" id="jikubox"></i> 
   <span class="badge badge-secondary">0</span></button>
</form>

Saved IDs will be set in name="varPostId" value=""

Now the tricky part which is confusing me, so localStorage can only have strings so first of all on each page load I do:

var lines = localStorage.getItem("lines") ? 
JSON.parse(localStorage.getItem("lines")) : [];

Then since in the article page I have a save button to add the current article id in the array, I do:

<button type="button" class="save_post">SAVE</button>

JS

$(".save_post").on("click", function(e) {
  e.stopImmediatePropagation();
  if (localStorage.getItem("attempts") >= 2) { 
    alert('nope'); 
    return; 
  } else {

  // Here I set the id for each article which I saved before via php in a span 
    var thisId = $(".my_post_id").attr("data-id");

    var lines = localStorage.getItem("lines") ? JSON.parse(localStorage.getItem("lines")) : []; 
    lines.push(thisId);
    localStorage.setItem("lines", JSON.stringify(lines));
    console.log(lines);
    $("#input_post_id").val(JSON.parse(localStorage.getItem("lines")));
    var attempts = Number(localStorage.getItem("attempts"));
    localStorage.setItem("attempts", ++attempts);
    console.log(localStorage.getItem("attempts"));
    $("#jikubox span").text(localStorage.getItem("attempts"));
  }
});

Notice I have another localStorage: attempts, that is used to add or remove a number I set in a counter badge, basically an indicator which tells how many items I have in my "bag". Remember: max 2 and unique.

So finally on the form result page I have a button to remove added items and the following js is used:

$(".removeJiku").on("click", function(){

  // Here I set the id for each article, I do that with php
  // <span  class="removeId" data-thisPostId="<?php echo $idThisPost; ?>"></span>

  var removeThisId = $(".removeId").attr("data-thisPostId");
  $(this).parent().fadeOut();
  var attempts = Number(localStorage.getItem("attempts"));
  localStorage.setItem("attempts", --attempts);
  $("#jikubox span").text(localStorage.getItem("attempts"));
  lines.splice($.inArray(removeThisId, lines), 1);
  localStorage.getItem("lines", lines); 
  localStorage.setItem("lines", lines); 
  console.log(localStorage.getItem("lines"));
});

The logic is kinda ok but after I try few times, I eventually get empty lines array and the ids are not set to the input value. I think I over complicated the logic and I was wondering where and how I could simplify and correct it. I am looking into a single general bit of code which handles all of this without complicating the logic.

UPDATE

Thanks to an answer, one bit of code has been simplified and the counter will be set by checking the length of the ids in lines array so We can remove the whole code for the attempts local storage logic

$("#jikubox span").text(lines.length);

Upvotes: 1

Views: 2510

Answers (3)

akshaymarch7
akshaymarch7

Reputation: 58

Assume you store your IDs in an array-

var idList=["123","456"];

You can store IDs like this -

localStorage.setItem("idList",JSON.stringify(idList));

and fetch idList like this-

JSON.parse(localStorage.getItem("idList")).length

Just make sure to put validations all around.

P.S. No need to count the "attempts" as you can anytime use the below code to find the length of the idList, which can be 2 or any number you want

JSON.parse(localStorage.getItem("idList")).length

UPDATE:

To remove IDs-

function removeId(array, element) {
    const index = array.indexOf(element);
    array.splice(index, 1);
}

Fetch array from localStorage and pass it into this function -

idList  = JSON.parse(localStorage.getItem("idList"))

and call the function like this -

 removeId(idList,idToBeDeleted)

Upvotes: 3

CertainPerformance
CertainPerformance

Reputation: 371118

This block isn't doing what you want:

lines.splice($.inArray(removeThisId, lines), 1);
localStorage.getItem("lines", lines); 
localStorage.setItem("lines", lines); 

The second line is getting something from localStorage but isn't doing anything with it. It could be the equivalent of

lines.splice($.inArray(removeThisId, lines), 1);
['one line', 'another line'];
localStorage.setItem("lines", lines);

Just some random value that proceeds to get ignored by the interpreter.

The other problem is that you're setting localStorage.lines to the plain lines variable, not to JSON.stringify(lines).

Note that you can simplify your syntax noise just by doing

localStorage.lines = JSON.stringify(lines);

and

const lines = JSON.parse(localStorage.lines || '[]');

Upvotes: 1

Lasithds
Lasithds

Reputation: 2291

localStorage.getItem('item') only accepts one parameter, which will return the value if it exists in the local storage and will return null item doesn't exist.

localStorage.setItem(item, value) accepts two parameters. item which is a key and the value which is to be saved for the key. If item is already set it will overwrite the value.

Upvotes: 0

Related Questions