LocalStorage not keeping values - javascript

I have a form that whenever I add info it should keep it in localStorage so I cant then retrive it from a global variable.
But on refresh it only gives back the last input I did and its not really storing anything.
help please
let todoList = [localStorage.getItem("list")] || [];
newTask.addEventListener("submit", addList)
function addList(e){
e.preventDefault();
let input = document.querySelector(".new-list input")
newListName = input.value;
input.value = ""
newTaskList.push(newListName)
//todoList.push(newListName)
localStorage.setItem("list", newListName);
}

Storing Your Array as a String
In order to use local storage with our array, we'll need to convert our array into a string using a method that makes it easy for us to unconvert later. The way convert an array into a string is by using the JSON stringify function.
Let's say you have the following array called movies:
var movies = ["Reservoir Dogs", "Pulp Fiction", "Jackie Brown",
"Kill Bill", "Death Proof", "Inglourious Basterds"];
Using the stringify function, your movies array can be turned into a string by using the following syntax:
JSON.stringify(movies)
Since we want to store everything into our local storage, when you put it all together, you get the following:
var movies = ["Reservoir Dogs", "Pulp Fiction", "Jackie Brown",
"Kill Bill", "Death Proof", "Inglourious Basterds"];
localStorage.setItem("quentinTarantino", JSON.stringify(movies));
Notice that my data is being stored under the key called quentinTarantino.
Retrieving Your Data
Storing your data is only part of the fun. A very important part of all this is being able to retrieve your data and get back to using it like an array. This involves first retrieving your data as a string:
var retrievedData = localStorage.getItem("quentinTarantino");
My retrievedData variable is storing the values returned by my local storage item whose key is quentinTarantino. This data is currently in the form of a string.
To convert from a string back to an object, use the JSON parse function:
var movies2 = JSON.parse(retrievedData);
Once you have done this, the movies2 variable will point to the parsed data which is, as you can guess, an array. You can call all of the array methods on your movies2 Array object just like you always would for any old array.

Related

Access nested object values from local storage

How to get nested object values from localstorage.
For example:
"metadata":"{
"receiver":{"name":"John"},
"document":{"type":"Sample doc"},
"issuer":{"signatory":"Admin2"}}",
"options": "{"title\":"Document Title","expireOn":"2022-03-12T00:00:00.000Z"}"
I need to store and get values of name:john, type:sample, signatory:Admin.
localStorage.setItem('metadata', JSON.stringify(data.metadata));
let metadata = localStorage.getItem('metadata');
console.log('metadata: ', JSON.parse(metadata));
Thank you.
At first you should get the localStorage values and convert that to a JavaScript Object.
let metadata = JSON.parse(localStorage.getItem('metadata'))
Then you can easily get or store data.
// Store
metadata.receiver.name = 'example'
// Get
let name = metadata.receiver.name
You can do this way for other values also.
Have tried to save and get your JSON in localstorage.
Steps for getting nested object value.
Step 1: Sample JSON
var data = {"metadata":{"receiver":{"name":"John"},"document":{"type":"Sampledoc"},"issuer":{"signatory":"Admin2"}},"options":{"title":"DocumentTitle","expireOn":"2022-03-12T00:00: 00.000Z"}};
Step 2: Converting JSON Object to a String format and Save in
Localstorage window.localStorage.setItem("metadata", JSON.stringify(data.metadata));
Step 3: Fetch Stringify JSON from localstorage and parse var metadata = JSON.parse(window.localStorage.getItem("metadata"));
Step 4: Fetch nested Object value console.log(metadata.receiver.name)
Hope this answer is useful.

How to save multiple form values as a consolidated String in Local Storage and retrieve them to be displayed on the browser

I'm trying to create a 'Notes' application which is basically a form that the user uses to enter 2 values, a name and a note.
I am displaying the 2 values as a 'consolidated note' on the browser with a delete button.
There can be any number of notes entered using this form.
How can I save the consolidated notes(i.e with Creator's name and the actual content of the note) in a string or array in the Local Storage and then retrieve it to be displayed on the browser when the browser reloads?
I understand that we save it using JSON.stringify and retrieve the data from the Local Storage using JSON.parse, but I'm unsure of how to save these multiple notes in the LOCAL Storage and retrieve them. Please help!
function addNoteLocalStorage(){
let notes = getNotesFromStorage();
//creating the key-value pairs
let creator = document.getElementById('creator').value;
let note = document.getElementById('note').value;
obj.creator = creator;
obj.note = note;
let jsonstring = JSON.stringify(obj);
//create an array and push the string to the Object Array
objArray.push(jsonstring);
//store the new note
localStorage.setItem('notes', objArray);
}
The above code saves more than one note in the Local Storage.
Currently, this is how the array looks when stored in LS.
{"creator":"dgfdxsf","note":"dsgdsg"},{"creator":"sfs","note":"asd"}
How can I retrieve the values back into an object so that I can display each creator and note associated with that creator ?
Create an object of the values you get from the form.
var obj = {
creator : note
}
Now store this object in the local storage by stringifying in the same as you are doing (JSON.stringify). While retrieving, do a JSON.parse to retrieve the object.
If you have multiple objects like these, push them into an array and store that array in the local storage.
There is no need to convert a string to a JSON string, so you can play with your data without the need for stringify() and parse(). If you save the notes as array, however, you will need to do that.
// Add Note to Local Storage
function addNoteLocalStorage(){
//get saved notes. Set notes to empty string if it's the first time.
let notes = localStorage.getItem('notes') || '';
console.log("Notes return: "+notes);
//creating the key-value pairs
let creator = document.getElementById('creator').value;
let note = document.getElementById('note').value;
let consolidatedNotesString = creator+":"+note;
//append the new note to the existing note
notes += '\n'+ consolidatedNotesString;
//store the new note
localStorage.setItem('notes', notes);
}
With your edited question, you're saving notes in the form of array of objects, in which case you will of course need to stringify and parse back the notes. One issue with your current code is that you're converting to string the objects(notes) but you save the array which contains the notes as it is. stringify the whole array instead and that's enough. And the way you access the stored notes is by the getItem method and parse it to get back the array. Make sure to save the empty objArray as notes in the local storage before calling addNoteLocalStorage function though, or you will need to check if notes are already in the storage before trying to parse it.
const objArray = [];
localStorage.setItem('notes', JSON.stringify(objArray));
function addNoteLocalStorage(){
objArray = JSON.parse(localStorage.getItem('notes'));
//creating the key-value pairs
let creator = document.getElementById('creator').value;
let note = document.getElementById('note').value;
//push the string to the Object Array
objArray.push({creator, note});
//store the new note
localStorage.setItem('notes', JSON.stringify(objArray));
}
//And to get the first note and creator for example, you write like:
let noteArray = JSON.parse(localStorage.getItem('notes'));
let firstNoteCreator = noteArray[0].creator;
let firstNote = noteArray[0].note;

JQuery Mobile JSON Stringify

I'm new in jquery mobile. I'm doing a shopping list application for my school assignment and I'm requested to store objects in local storage.
Each item must include the following information: item Name, item quantity and a Boolean is_bought.
I wish to store all items data into one JSON string. Items data is entered by user from an other page.
My problem is
1)How items can be stored in local storage through JSON stringify.
2)How items data can be retrieved from JSON string to be represented into a list.
First: If I understood you right you have an object(json) structure like:
{
"name": "cheese",
"quantity": 2,
"is_bought": false
}
If not (in question you have no key(name) for your variables) your structure must be like I showed for having an access to each variable in the object.
Second: About localStorage. It is limited to handle only string key/value pairs, so you can't just save an object in it. You have to use JSON.stringify() to parse your object into the string and save in localStorage, then, after retrieving, use JSON.parse() to parse it back. The code could look like this:
var item = {"name": "cheese", "quantity": 2, "is_bought": true};
// Store item into localStorage
localStorage.setItem('item', JSON.stringify(item));
// Retrieve item from localStorage
var retrievedItem = localStorage.getItem('item');
var parsedItem = JSON.parse(retrievedItem);
EDIT: TO STORE MULTIPLE ITEMS
So, if your question is about storing multiple items and distinguishing them, and if your item's name is unique and you know what item is bought, you can store them into the localStorage with the key of item's name, e.g.
// You can do this in a for loop
localStorage.setItem('item_' + item.name, JSON.stringify(item));
// And to change (if you already know bought item's name), 'cheese' for example
var retrievedItem = localStorage.getItem('item_cheese');
var parsedItem = JSON.parse(retrievedItem);
parsedItem.is_bought = true;
// And save again in localStorage
localStorage.setItem('item_cheese', JSON.stringify(parsedItem));

How do I add one single value to a JSON array?

I am kind of new to the world of interface, and i found JSON is amazing, so simple and easy to use.
But using JS to handle it is pain !, there is no simple and direct way to push a value, check if it exists, search, .... nothing !
and i cannot simply add a one single value to the json array, i have this :
loadedRecords = {}
i want to do this :
loadedRecords.push('654654')
loadedRecords.push('11')
loadedRecords.push('3333')
Why this is so hard ???!!!
Because that's an object, not an array.
You want this:
var = loadedRecords = []
loadedRecords.push('1234');
Now to your points about JSON in JS:
there is no simple and direct way to push a value
JSON is a data exchange format, if you are changing the data, then you will be dealing with native JS objects and arrays. And native JS objects have all kinds of ways to push values and manipulate themeselves.
check if it exists
This is easy. if (data.someKey) { doStuff() } will check for existence of a key.
search
Again JSON decodes to arrays and objects, so you can walk the tree and find things like you could with any data structure.
nothing
Everything. JSON just translates into native data structures for whatever language you are using. At the end of the day you have objects (or hashes/disctionaries), and arrays which hold numbers strings and booleans. This simplicity is why JSON is awesome. The "features" you seek are not part of JSON. They are part of the language you are using to parse JSON.
Well .push is an array function.
You can add an array to ur object if you want:
loadedRecords = { recs: [] };
loadedRecords.recs.push('654654');
loadedRecords.recs.push('11');
loadedRecords.recs.push('3333');
Which will result in:
loadedRecords = { recs: ['654654', '11', '3333'] };
{} is not an array is an object literal, use loadedRecords = []; instead.
If you want to push to an array, you need to create an array, not an object. Try:
loadedRecords = [] //note... square brackets
loadedRecords.push('654654')
loadedRecords.push('11')
loadedRecords.push('3333')
You can only push things on to an array, not a JSON object. Arrays are enclosed in square brackets:
var test = ['i','am','an','array'];
What you want to do is add new items to the object using setters:
var test = { };
test.sample = 'asdf';
test.value = 1245;
Now if you use a tool like FireBug to inspect this object, you can see it looks like:
test {
sample = 'asdf,
value = 1245
}
Simple way to push variable in JS for JSON format
var city="Mangalore";
var username="somename"
var dataVar = {"user": 0,
"location": {
"state": "Karnataka",
"country": "India",
},
}
if (city) {
dataVar['location']['city'] = city;
}
if (username) {
dataVar['username'] = username;
}
Whats wrong with:
var loadedRecords = [ '654654', '11', '333' ];

How to store temporary data at the client-side and then send it to the server

I need to store data temporarily at the client-side to allow users to add, edit or delete items without having to query the server for each of these actions; just when the user finishes adding items and clicks on the Add button, the list is sent to the server to be saved permanently.
This image describes what I want to achieve.
I know I have to use arrays in JavaScript, but I don't know how to create one to store objects (in this case Detail which contains :id, price and description).
I hope you can help me out.
Thanks in advance.
PS: I'm using JSP and... sorry for my English
Sure, since it's a table it makes sense to have an array of objects. Note that an object is surrounded by curly braces and an array is surrounded by brackets:
var myArray = []; // Initialize empty array
var myObject = {}; // Initialize empty object
This should accomplish what you need:
// Initialize variables
var newEntry, table = [];
// Create a new object
newEntry = {
id: '',
price: '',
description: ''
};
// Add the object to the end of the array
table.push(newEntry);
Which is the same as this:
// Initialize array
var table = [];
// Create object and add the object to the end of the array
table.push({
id: '22',
price: '$222',
description: 'Foo'
});
You can now access properties like this:
table[0].id; // '22'
On modern browsers, if you want the data to persist across sessions (like cookies) you could use the sessionStorage or localStorage objects.
When you want to send the data to the server, you'll send a JSON version of the table across the wire:
var data = JSON.stringify(table);
You can create an Array of your custom Detail objects pretty easily with object literals:
var details = [];
details.push({id:'abc1234', price:999.99, description:'Tesla Roadster'});
details.push({id:'xyz5678', price:129.99, description:'Land Rover'});
Then you can post your data to the server when the user clicks "Add."
Sounds like a good job for JSON.

Categories

Resources