Tips for repairing my Bookmark local-storage tool

My Bookmark Service, which stores result items with a JSON structure, is experiencing issues. It seems that the problem lies in the array not functioning properly with the local storage feature.

I have attempted to use JSON.stringify on my items.


    var key = 'fud_bookmarks';
    var bookmarks = [];

    this.addBookmark = function(resultItem) {
      var bookmarks = this.getBookmarks();
      bookmarks.push(resultItem);
      return setBookmarks(bookmarks);
    };

    this.deleteBookmark = function(resultItem) {
      var bookmarks = this.getBookmarks();
      var i = bookmarks.indexOf(resultItem);
      if (i >= 0) {
        bookmarks.splice(i, 1);
        console.log(bookmarks)
        return setBookmarks(bookmarks);
      }
      return false;
    };

    this.getBookmarkCount = function() {
      return getBookmarks().length;
    };

    this.getBookmarks = function() {
      var bookmarks = localStorage.getItem(key);

      if (!bookmarks) {
        bookmarks = [];
      }

      return bookmarks;
    }


    function setBookmarks(bookmarks) {
      return localStorage.setItem(key, bookmarks);
    }

The resulting items are structured as follows.


    {
      id: "112",
      docType: "doctyp117",
      title: "Abschließender Bericht über die Arbeit des Kunsts…- September 1944, Exemplar für Tieschowitz, o.D.",
      type: "Archivbestand",
      description: null,
      …
    }

    $$hashKey: "object:455"

    archive: {
      id: "24",
      title: "Familienarchiv der Grafen Wolff Metternich zur Gracht"
    }

Currently, I am encountering the following error in the console =>

bookmarks.push is not a function
    at Object.addBookmark (bookmark.js:12)

Answer №1

Remember, localStorage can only store string values, not objects. Make sure to stringify an Array before storing it.

function saveBookmarks(bookmarks) {
   return localStorage.setItem(key, JSON.stringify(bookmarks));
}
this.retrieveBookmarks = function () {
  var bookmarks = JSON.parse(localStorage.getItem(key));
...

Visit the documentation for Window.localStorage on MDN

If the value in storage is not a valid JSON, using JSON.parse will throw an error. To handle this, consider using try-catch blocks:

this.retrieveBookmarks = function () {
  var bookmarks;

  try {
    bookmarks = JSON.parse(localStorage.getItem(key));
  } catch (e) {
    bookmarks = [];
  }
...

For deleting a bookmark, the method should look something like this:

this.deleteBookmark = function (bookmarkItem) {
  var index = 0;

  let bookmarks = this.retrieveBookmarks();
​
  for (;index < bookmarks.length - 1; index++) {
    if (bookmarkItem.id === bookmarks[index].id) {
      break;
    }
  }

 if (index >= 0) {
   bookmarks.splice(index, 1);
   console.log(bookmarks)
   return saveBookmarks(bookmarks);
 }
 return false;
}

Answer №2

Here's a suggestion: Make sure to verify whether bookmarks is not an object before returning an empty array. Remember that in JavaScript, an Array is also considered a type of object.

this.getBookmarks = function() {
      var bookmarks = localStorage.getItem(key);
      if (typeof bookmarks !== "object") {
        bookmarks = [];
      };

    return bookmarks;
    };

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

What is the reason I do not need to decode or parse a JSON string created by PHP in JavaScript?

When setting variables in a JS script, one way to do it is by wrapping them in JSON like this: <?php // Variables for JS $vars = array( 'fetchPath' => "$home/my-url.php", ); ?> <script> var phpVars = <?php echo json_encode( ...

Utilizing the jQuery slideToggle method on the specified target element

I'm encountering an issue with jQuery slideToggle, and here's the code I have: $(".dropdownmainmenu").click(function(){ $(this).children(".showmenu").slideToggle(); $(this).toggleClass("activemainmenu"); $(this).find(".showarrowmainmen ...

Choose a numeric value and then adjust it to display with exactly two decimal places

My goal is to create a code that achieves the following tasks: Add an ID to every nth child Round the number in each nth child to 2 decimal places Prefix the numbers with a pound sign (£) Loop through until all the nth children in a table are processed ...

Performing an asynchronous AJAX request to a PHP script to compute the total sum and retrieve

I have created an HTML table and utilized AJAX to send a POST request with two arrays. The first array is named rowValues and contains three arrays, one for each row. The second array is called columnValues and also has three arrays, one for each column. ...

Incorporate External Web Page Information by Clicking a Button

Apologies if this question has already been asked, but despite my efforts to explore the available resources, I have not found a solution to my issue. I currently have an input field where users can enter their website, keyword, or industry. When they cli ...

Once logged out in Vue Router, the main app template will briefly display along with the login component

After clicking the logout button, I am experiencing an issue where my main UI remains visible for a few seconds before transitioning to a blank page and displaying the login form component. This behavior is occurring within the setup of my App.vue file: & ...

A guide on consolidating all app.use statements into a single shared file

My application's starting point, the index file, contains multiple instances of app.use. For example: app.use( if (!req.contextToken && req.contextTokenchecked) { req.queryToFirebase = false; req.contextTokenchecked = tru ...

Use JavaScript's Array.filter method to efficiently filter out duplicates without causing any UI slowdown

In a unique case I'm dealing with, certain validation logic needs to occur in the UI for specific business reasons[...]. The array could potentially contain anywhere from several tens to hundreds of thousands of items (1-400K). This frontend operation ...

Button element experiencing unexpected issues with ng-disabled in AngularJS

I've implemented a new button that should be active when the page loads and then disabled when data is being saved (using a save button). Essentially, this new button should be inactive whenever the save button is active. Angular code : <input id ...

Insert data into a drop-down menu and organize it

When I choose a value in one Select, the other options are removed and the previous value is added to them. How can I use JQuery to add the previous value to Select and then sort it alphabetically? ...

I'm trying to figure out how to resolve this issue in IE: SCRIPT1003: A colon is expected

let dataOptions = { @foreach($options as $option) @if($option->option_type == 0) Choose_{{ $option->id}}, @endif @if($option->option_type == 1) ...

What could be causing the issue of messages not displaying while incorporating connect-flash with res.locals in express.js and ejs templating?

Here are some snippets of code that may be useful. Connect-flash is designed to display messages on test1 and test2, but there seems to be an issue with displaying messages for test 3: user registration when all three tests are redirected to the same &apos ...

How can I merge two arrays in JavaScript to form a table?

I have two sets of data stored in arrays. This is how my information is organized: var apples = [ "red", "green", "yellow"]; var oranges = [ "sweet", "sour"] The goal is to create tables with the same number of rows as there are elements in the apple arr ...

Making a RESTful API call using JavaScript

Can someone help me with making a call to a REST API using JavaScript, Ajax, or jQuery? curl -v -X PUT -H "Content-Type: application/json" -H "Accept: application/json" -X PUT --user user:password http://url -d "{\"name\": \"Marcus0.2\ ...

Why does the Node.js REST API keep throwing errors after I try to create just one record?

I encountered a back end issue recently. I have developed a simple API with just a post endpoint. The intention is to post data using the req.body. Oddly enough, it works perfectly fine the first time but when I attempt it again, I receive an error message ...

Enhance your message inbox experience with jQuery/Javascript features inspired by Gmail, including the ability to select all messages with a checkbox and

It is truly satisfying to be here working on developing a private message inbox for my website, especially after successfully implementing a complete user signup/login and activation system. A few months ago, I never believed I had enough patience to grasp ...

Tips for displaying an alpha-numeric keyboard in a React Native application

I am struggling to display an alpha-numeric keyboard in my React-Native App. I have tried various values for the keyboardType prop, but none of them seem to work for me. If anyone has any suggestions on how I can achieve this, please do share your ideas w ...

PHP script not being triggered by Ajax upload

After identifying and fixing errors through the Chrome console log, I am facing a new issue where the PHP script responsible for processing the data is not being called. <legend><strong>Choose a machine model</strong></legend> < ...

html inserting line break using label

I am attempting to dynamically set text to a label using jQuery. However, I am having trouble getting the <br> or \n to create new lines. Instead, all the text displays on the same line and wraps around. If you want to see my code in action, ch ...

Optimizing CSS With jQuery During Browser Resize

I am currently facing an issue with recalculating the height of the li element during window resizing or scrolling. Strangely, on page load, the height is no longer being re-calculated and set to the ul's child height. Here is the code I have written ...