The local storage is empty

I've encountered an issue with localStorage. Here is a snippet of my code:

var defaultReportData = {
  'station': 'DR P3',
  'days': 'Mon, Tue, Wed, Thur, Fri',
  'startHour': '06:00',
  'endHour': '18:00',
  'demography': 'Cover: All'
}

localStorage.setItem('defaultReportData', JSON.stringify(defaultReportData));

// Returns null
console.log(localStorage.getItem('station'));

After loading the page, if I simply type "localStorage" in my console, the object displays correctly. However, when I try to retrieve a specific value from localStorage, it returns null.

What could be causing this issue?

Answer №1

Check out this working example.

To access the station from the returned string, you need to parse it as JSON like so:

var storedData = JSON.parse(localStorage.getItem('storedData'));
console.log( storedData.station );

Answer №2

To access the information stored in localStorage, you must use the identical key (defaultReportData) that was originally used when saving the data. Following that, you need to convert the string data into a JSON Object.

var savedData = JSON.parse(localStorage.getItem('defaultReportData'));
console.log(savedData.station);

Answer №3

To use this solution, simply copy and paste the code into your console

    var defaultReportData = {
      'station': 'DR P3',
      'days': 'Mon, Tue, Wed, Thur, Fri',
      'startHour': '06:00',
      'endHour': '18:00',
      'demography': 'Cover: All'
    }

    window.localStorage.setItem('defaultReportData', JSON.stringify(defaultReportData));

    // This will return null

    var itemPref = window.localStorage.getItem('defaultReportData')

    var resultObject = JSON.parse(itemPref);

    console.log(resultObject.station);

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

Is it possible to use Ajax post with localhost on Wamp server?

Looking to execute a basic POST function using Ajax on my localhost WAMP server. Here's the code I have: function fill_table() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari ...

Three.js dynamic bone animation: bringing your project to life

Can transformations be applied to the bones of a 3D model in three.js to create a dynamic animation? I attempted to move and rotate the bones of a SkinnedMesh, but the mesh did not update. loader = new THREE.JSONLoader(); loader.load(&apos ...

The rails application is flooding the JSON with unnecessary data

Needed result: only extract data from events, such as: [{"id":600,"title":600,"start":"2018-10-17T15:24:06.000Z","end":"2018-10-17T17:11:06.000Z","color":"green"} [{"id":601,"title":601,"start":"2019-10-17T15:24:06.000Z","end":"2018-10-17T17:11:06.000Z"," ...

What is the most efficient way to dynamically add a class to multiple elements in AngularJS using ng-click?

On my HTML page, I have 2 lists that I want to modify so that when an option is clicked, it adds a class altering the background-color of the li element to red. If the same option is clicked again, it removes the class and reverts back to white: This is t ...

Exploring the intricacies of Bower and enhancing dependency management

Currently, I am working on developing a project named myapp using angularJS along with Yeoman Generator. This project involves utilizing Bower to manage dependencies and Grunt to wiredep those dependencies into the index.html file (which essentially genera ...

How can I retrieve the decimal x and y coordinates when the mouse is moved in Typescript Angular?

I am in the process of transitioning my user interface from Flash/Flex, where it stores values in decimal format. I need to access and reuse these values. Here is a demo showcasing my problem. Here is a snippet: import { Component, Input } from '@an ...

Make the current tab the active tab with the help of AngularJS

I have a set of five tabs that are functioning correctly. However, when I refresh the page, the active tab reverts back to its default state instead of staying in its current active state. Can anyone help me identify where I may be making a mistake? Here ...

Sending information and HTML content from PHP to JavaScript using JSON

As a beginner to this, I acknowledge any noticeable mistakes. I am attempting to utilize an ajax call from Javascript to randomly select a movie from a database, generate some html containing information about the movie, and also return an array of inform ...

The time zones between Node 8 and Node 11 are not the same

Executing a basic new Date().toString() command produces different results on Node 11 compared to Node 8. In Node 11, the output includes the full timezone abbreviation like this: 'Fri May 10 2019 10:44:44 GMT-0700 (Pacific Daylight Time)' On t ...

Is it necessary to release a new library version for non-functional updates?

As the maintainer of several JavaScript libraries, I often find myself needing to update dependencies that don't necessarily require any functional changes. This is especially true when my library is not impacted by a breaking change in one of its dep ...

What are the reasons for the POST method malfunctioning in a mobile web application?

Currently, I am in the process of developing a mobile web application using PhoneGap. At the moment, I am successfully passing data between the client (HTML page on the mobile device) and the server (PHP on the server) using the GET method. However, when a ...

How can I transform Json data into XML format with namespaces included?

Here is an example of a json string: "{ "RSS": { "Channel": { "item": [ { "title": "Overlay HD/CC", "guid": "1", "description": "This example shows tooltip overlays for captions and quality.", "j ...

The console logs indicate success for every call, but unfortunately Twitter is not displaying the retweets

Hey there! I'm having some trouble with calling a function and it's not working as expected. var T = new Twit(config); var retweet = function() { T.get('search/tweets', {q:'#python3, #nodejs, python3, nodejs,', count :5 }, f ...

Custom calendar control vanishes on postback in ASP

After creating a custom calendar control that works smoothly for the most part, I encountered an issue. Whenever it is posted, the control disappears even when the user is still hovering over it. I want users to be able to change months, dates, or anythi ...

The default styling of Next.js react-chatbot-kit is not functioning properly

import Chatbot from 'react-chatbot-kit' import config from './config' import ActionProvider from './actionProvider' import MessageParser from './messageParser' const ChatBotFlight = () => { return ( <div> ...

Comparing non-blocking setTimeout in JavaScript versus sleep in Ruby

One interesting aspect of JavaScript is that, being event-driven in nature, the setTimeout function does not block. Consider the following example: setTimeout(function(){ console.log('sleeping'); }, 10); console.log('prints first!!') ...

Creating a JSON array from data within a <td> element is a straightforward process

I'm looking to convert this data into JSON format. Can someone assist me with the process? I'm not very familiar with using jquery and php. The html code is structured like this <form> <table> <tr> < ...

In Java, converting a date to a JSON String results in the date decreasing by one day

A unique method has been developed to extract a date from an alpha-numeric String. For example, if the String is Y04051000547GF, the resulting date will be Tue May 04 00:00:00 IST 2010. public static Date getDateFromGITID(String gitId) { Date date ...

Testing asynchronous functions with Mocha

Currently, I am in the process of developing a node wrapper to interface with an external api. One particular challenge I am facing is testing the asynchronous functionality of the createJob method. Provided below is the test case code: api_key = "test_0d ...

The ">" character in JSON data is encoded as u003c

I am working with a JSON object that contains a string element. This string includes the characters ""<RPC>"". In my ASP.NET server code, I take this JSON object named rpc_response and add it to the data in a POST response using the following steps: ...