Problems encountered while persisting JSON data within sessionStorage

My goal is to leverage HTML5 sessionStorage to store data retrieved from an external API, enabling me to cache the data for future use within the same session. This way, I can avoid redundant calls to the API and improve performance by using locally stored data.

function getItemWithTooltip(item_id, div_id) {
var xmlhttp2 = new XMLHttpRequest();
var url2 = "https://api.guildwars2.com/v2/items/"+item_id;

xmlhttp2.onreadystatechange=function() {if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {parseItemTooltip(xmlhttp2.responseText);}};
xmlhttp2.open("GET", url2, true);
//xmlhttp2.send();

var item;

var cache_enabled = true;
// Implement caching for quicker page loads
if (cache_enabled == true){
    if (Storage !== void(0)) {
        // Check if data is already cached
        if (sessionStorage[String(item_id)]) {
            item = JSON.parse(sessionStorage[item_id.toString()]);
        }
    }
}

if (item == null){
    xmlhttp2.send();
}

  function parseItemTooltip(response) {

    if (item == null){
        // Store data in cache
        if (cache_enabled == true){sessionStorage.setItem(item_id.toString(), JSON.stringify(response));}
        
        item = JSON.parse(response);
    }
    //..Additional code removed for brevity..
  }
}

Answer №1

It seems like the issue might stem from the fact that you are using JSON.stringify on the response before storing it. The response is already a string, so applying JSON.stringify to it will essentially "double-stringify" it. When you attempt to parse it afterwards, you'll only end up with the original string.

You're performing both JSON.stringify and JSON.parse on the response text. This approach doesn't make sense for JSON data; you should ideally choose one of these methods. Stringifying a string will result in it being "double-stringified", while attempting to parse an object directly will throw an error since JSON.parse expects a string input.

Imagine your response text looks like this:

'{"property":"value"}'

Initially, it's a string. Once you stringify it, it transforms into:

'"{\"property\":\"value\"}"'

By parsing this double-stringified version when retrieving it via sessionStorage, you'll only receive the raw string again. You'd have to parse it once more to retrieve the desired object.

When you directly parse the response text, you'll get the correct object representation:

{
  property: "value"
}

To rectify this, store the response text in sessionStorage without applying stringification.


Furthermore, it appears that you're solely calling parseItemTooltip within the request's state change handler. Consequently, it won't be invoked when accessing the cached item. Analyzing your complete code, it seems like most operations are encapsulated within this function, necessitating explicit invocation outside of request scenarios.

Answer №2

After spending a frustrating hour grappling with my code, I finally managed to pinpoint the problem, and it turned out to be something incredibly simple, as it often is.

The solution was to switch these two lines around:

    getItemWithTooltip(item.id, div_ID);
    document.getElementById("id01").innerHTML = out;

To this:

    document.getElementById("id01").innerHTML = out;
    getItemWithTooltip(item.id, div_ID);

The reason behind this change was that the div was being filled before it was even created. Previously, this wasn't an issue because the data was fetched while waiting for the remote server response. However, with the data now cached in sessionStorage, the retrieval happened so quickly that the order of execution became crucial. It's always important to pay attention to the logical progression of steps.

I want to express my gratitude to everyone who helped debug this issue. Your quick responses and friendly assistance made my first experience on this website truly enjoyable. Thank you all!

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

Node.js causing error: TypeError - Unable to access property 'forEach' as it is undefined

Currently in the process of developing my initial node/express application and closely following this tutorial. I have reached a stage where I am attempting to retrieve all JSON data, store it in an array for transmission to the template, and eventual ren ...

Troubleshooting: Ruby on Rails and Bootstrap dropdown issue

Having some issues with implementing the bootstrap dropdown functionality in my Ruby on Rails application's navigation bar. I have made sure to include all necessary JavaScript files. Below is the code snippet: <div class="dropdown-toggle" d ...

Ways to loop through the outcome of an array within the Document Object Model (DOM)

https://i.sstatic.net/Cmfx0.jpg Hey there, I'm currently facing an issue while trying to loop through an array to access the class of tag.highlight within a span that only becomes active after being iterated over 30 times with span.tag. My main goal ...

Update information interactively in Vuejs for all stored data

I am facing an issue with my code where the totalUserPosts value is returning as Zero after an AJAX call, and I need to find a solution for this problem. new Vue({ el: "#app", data: { totalUserPosts:0, }, methods:{ getPostsAjax () { $.ajax({ ...

Angular 2: Enhancing Tables

I am looking to create a custom table using Angular 2. Here is the desired layout of the table: https://i.sstatic.net/6Mrtf.png I have a Component that provides me with data export class ResultsComponent implements OnInit { public items: any; ngO ...

Having trouble with angular.fromJson parsing a local JSON file?

I am currently trying to parse a local json file (data.json) using angular.fromJson, but I am not very familiar with this process. I came across a helpful post on How do I update/add to a json file that I have been following. The issue I am facing is that ...

Fade-in animation of a clock on an SVG image

I am trying to achieve a unique fade-in effect for an SVG image in my HTML. The challenge is to make the fade-in start from the top of the image and progress in a circular motion until it completes a full circle. An example of the effect I am aiming for is ...

Using ElectronJS requires the usage of the import keyword to load ES Modules

I've recently delved into Electron development by exploring the Electron Docs. I opted for ES6 syntax with import/export, while the documentation showcased the use of require. To align with ES Module standards, I updated my package.json file with typ ...

Why does the Angular page not load on the first visit, but loads successfully on subsequent visits and opens without any issues?

I am currently in the process of converting a template to Angular that utilizes HTML, CSS, Bootstrap, JavaScript, and other similar technologies. Within the template, there is a loader function with a GIF animation embedded within it. Interestingly, upon ...

Separating ReactJS methods and useState functionality into their own files is a best practice for organizing

One of my components is called Invoice.js, which currently has over 1000 lines of code. I am looking to extract certain methods and their related useState functionality into a separate file. Within this component, there is an array named items that gets f ...

Tips for avoiding the default rendering of Nuxt 3 layout?

After reviewing the Nuxt 3 documentation and finding it lacking in explanation, I turned to the Nuxt 2 docs. According to them, the default layout should be replaced by a specific layout specified within the name property of the <nuxt-layout> compone ...

I am having trouble formatting dates using the Moment.js library on Internet Explorer, it keeps returning

When using the moment.js date library to format a date, I encountered an issue on IE where I would get NaN in the output. This problem did not occur on other browsers such as Chrome and Firefox. var value = "2015-11"; moment(value).format("YYYY-DD-01 00: ...

Compiling a collection of JSON files containing just a single element within each file

I have 4 separate JSON files stored in two different folders: folder1 and folder2. Each JSON file includes the date, the body, and the title. Contents of folder1.json: {"date": "December 31, 1989, Sunday, Late Edition - Final", "body": "Frigid temperatur ...

Simultaneous malfunction of two ajax forms

I have a dilemma with two boxes: one is called "min amount" and the other is called "max amount." Currently, if I input 100 in the max amount box, it will display products that are priced at less than $100. However, when I input an amount like $50 in the m ...

The button is being obscured by an invisible element at coordinates (x,y), making it unclickable

Having trouble with Selenium and Chrome Webdriver when trying to click a button due to an invisible element <div class="modal-overlay" style="display: block;"></div> covering the entire page. How can I navigate around this obstacle? I attempte ...

What causes my multipart form data to transform into JSON format?

Currently, I am facing an issue where I need to send a POST request to an API that requires multipart form-data. The request should include one record with the key 'json' and the value as a string containing a JSON object. I am attempting to ach ...

Switch the toggle to activate or deactivate links

My attempt at coding a switch to disable and enable links using CSS is functional in terms of JavaScript, but the appearance is not changing. I am lacking experience in this area. Here is my HTML Button code: <label class="switch" isValue="0"> ...

Loopback: Unable to access the 'find' property as it is undefined

I've come across a few similar questions, but none of the solutions seem to work for me. So, I decided to reach out for help. I'm facing an issue while trying to retrieve data from my database in order to select specific parts of it within my app ...

Utilizing JSON in Django's template system

Currently, I am utilizing Django to build a website. To integrate JSON into HTML, I have configured it to respond with JSON to the template. However, when attempting to incorporate JSON data within the HTML, the data does not display. Below is my code: v ...

Adding fresh information to the conclusion of a JSON file using PHP

I have a predefined JSON and I am looking to append new data as an element of the existing JSON. I want to add the new data at the end of the JSON as a new element. $jsonData = array(); if (!empty($json_mainQuot)) { $jsonData['mainQuot'] = $js ...