localStorage, i cant seem to call the data - javascript

var dataArray = [];
localStorage.itemListRecord = JSON.stringify(dataArray);
dataArray = JSON.parse(localStorage.itemListRecord);
var dataObj = {
listItem: textInput,
};
dataArray.push(dataObj);
I am trying to save the data on my todo list, I get the items pushed into an object, that i "stringify" and "parse"...
But I am not quite sure how I then call the saved data..
And it seems like the items ain't getting to the localStorage at all..
https://jsfiddle.net/headbangz/kn0bw6yw/

This example should work.
var textInput = "example";
var dataObj = {
listItem: textInput,
};
var dataArray = [];
dataArray.push(dataObj);
localStorage.setItem("itemListRecord", JSON.stringify(dataArray));
dataArray = JSON.parse(localStorage.getItem("itemListRecord"));
dataArray.push(dataObj);
localStorage.setItem("itemListRecord", JSON.stringify(dataArray));

I notice that when the script starts you are immediately clearing the localStorage.itemListRecord location that you are using, before you try to read from it. So, it will always be empty upon initialization and this script will never be able to use what is there:
// Data Object
var dataArray = [];
// CHANGED: I commented out the line below so that the localstorage is not cleared
// localStorage.itemListRecord = JSON.stringify(dataArray);
dataArray = JSON.parse(localStorage.itemListRecord);
// CHANGED: added these lines only for debugging
console.log('existing data');
console.log(dataArray);
Also, I notice that there is not any code yet that will add to the local storage, when a new todo list item is added:
function listTodoItem(textInput) {
var dataObj = {
listItem: textInput,
};
dataArray.push(dataObj);
// CHANGED: added this line to update localstorage whenever an items is added to the list
localStorage.itemListRecord = JSON.stringify(dataArray);
// CHANGED: added these lines only for debugging
console.log(dataArray);
console.log(dataObj);
Note that, even with these changes, the list still doesn't reflect what is in local storage, because it doesn't build the initial unordered list from what is in the dataArray. More code needs to be added for that too.
But with what I've suggested here, and looking at the output in the console log when you re-run the jsfiddle, you should be able to see that the localstorage part is working, and you can get past this bit.

I haven't seen that API
I use what is listed on Mozilla's site https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
Appears to be get and set okay in this example tied to your click handler
Check the console for logs
Per commentary below - exact click handler changed
// Add value from the input field
document.getElementById("new-btn").addEventListener('click', function() {
var itemValue = document.getElementById("my-input").value;
if (itemValue) {
listTodoItem(itemValue);
localStorage.setItem('data', JSON.stringify(itemValue));
console.log(localStorage.getItem('data'));
}
});

Related

Chrome.storage.local.set: can't set and push into array properly

I'm making a Chrome extension which has a feature to add strings from HTML form and store them in chrome storage. I want to push strings to one array, so every time I send a string from the form, it'll be added into the same array.
However, it doesn't store data correctly with my code.
document.getElementById('add-word-form').onsubmit = function(){
chrome.storage.local.get({ words:[] }, function(items) {
let newWord = document.getElementById('vocabulary').value;
let nextWord = items.words.push(newWord);
chrome.storage.local.set({ words:[nextWord] });
});
}
I'm guessing that I'm doing something wrong with chrome.storage.local.get() too, because I receive only numbers not actual string on console.log with code below...
chrome.storage.local.get({ words:[] }, function(items) {
console.log(items.words); // Array(1) // on first form submit
// [2] // on second attempt and same onwards
});
Could anyone see where I am doing wrong..?

How to store data in an array that is stored in a variable?

Following is my problem:
I am testing a system now, that has multiple ID's in every request. There are 2 ID's I want to store in an array and let them run again a response later.
Following is the Body I recieve
{
"id" = 1234;
"Name" = "Meier"
}
So, I store the ID normally with
var body = JSON.parse(responseBody);
postman.setEnvironmentVariable("ID", body.id);
with that I can store 1 ID in the variable, but can't put a second one in it. For that I would have to duplicate the request, set a second variable, change code everytime the needed cases are changed.
What I want to know now is: How can I store multiple ID's in a Environment Variable to compare them with a response at the end of the collection?
I'm not entirely familiar with postman, but if I'm understanding correctly and you want to store up the Id's from the response then you could use something like -
var body = JSON.parse(responseBody);
var storedIds = postman.getEnvironmentVariable("ID");
if(storedIds) {
storedIds.push(body.id)
} else {
storedIds = [body.id]
}
postman.setEnvironmentVariable("ID", storedIds);
Edit
From my own googling, it appears you cannot store arrays in environment variables in postman. Therefore you could try doing something like this -
var body = JSON.parse(responseBody);
var storedIds = postman.getEnvironmentVariable("ID");
if (storedIds) {
storedIds = storedIds.concat(',' + body.id)
} else {
storedIds = body.id
}
postman.setEnvironmentVariable("ID", storedIds);
Then when you want to read it back out to loop over it or whatever you want to do you can use
var idsArray = postman.getEnvironmentVariable("ID").split(',')
which will split the string up to give you an array.

Parsing a JSON object with Javascript, just won't work

I'm using this code to get a JSON file stored in the same folder.
var schedtotal = 0;
var requestURL11 = 'schedtotal.json';
var request11 = new XMLHttpRequest();
request11.open('GET', requestURL11);
request11.responseType = 'json';
request11.send();
request11.onload = function() {
window.superHeroes11 = request11.response;
populateHeader11(superHeroes11);
}
function populateHeader11(jsonObj) {
window.schedtotal = jsonObj.total;
console.log("populateHeader function has activated");
console.log(jsonObj);
}
The file looks like this:
{"total": 3}
It's valid JSON. I'm trying to extract the value of total using the same exact method that I've used successfully for all the other JSON parsings in the rest of the file (which I have not included here).
When populateHeader11 is called, it doesn't change schedtotal to equal total. It remains at its original setting of 0. The console log returns from the function as having activated and also returns the JSON file so I know it can access it at least.
I've tried changing .jsonObj.total to .jsonObj['total'] and it didn't change anything.
Previous times I've screwed around with this, it has sometimes returned an error saying it can't get 'total' from null. Now it just doesn't return anything in its current state. What is going on?
You need to parse the JSON string into an object before you try and access the total field.
var jsonString = "{\"total\": 3}";
var jsonObj = JSON.parse(jsonString);
console.log(jsonObj.total);

LocalStorage in Contact Manager (knockoutjs)

This app is a Contact Manager. And I want when user is filling the form and click save the contacts which appears to be stored in local storage so I could remove some of them etc. Adding and removing are working but it's not storing.
Here is the app:
http://jsfiddle.net/vpbj32Lh/
The problem in this lines:
self.load = function(){
self.contacts = localStorage.getItem("stored_contacts");
}
self.save = function(){
localStorage.setItem("stored_contacts", self.contacts);
self.contacts=localStorage.getItem("stored_contacts");
console.log(self.contacts.length);
}
If you delete this lines and "data-bind="click: save" in html file. It willbe adding and removing but not saving and loading
I've found a number of things to change in your code.
This is a fixed version:
JS
(function ContactManager(){
// ...
self.contacts = ko.observableArray();
self.addItem = function(){
self.contacts.push(new Contact(self.conName(), self.phone(), self.email(), self.address()));
}
// ...
self.load = function(){
// haven't tested, but probably won't work. I think you'd have to convert your JSON to observables
self.contacts = localStorage.getItem("stored_contacts");
}
self.save = function(){
self.addItem(); // calling it from here, not from your HTML form submit
// you have to convert to JSON to save in localStorage
localStorage.setItem("stored_contacts", ko.toJSON(self.contacts()));
}
ko.applyBindings(self.templateName);
})();
HTML
<form class="addContact" autocomplete="on">
<!-- ... -->
</form>
A couple of observations:
self.contacts = ko.observableArray(self.save); - this doesn't make any sense. You are initializing an observableArray with a function object. You are not even calling the function, you are passing the function. Either way, doesn't make sense here.
<form data-bind="submit: addItem" > and <button data-bind="click: save" type="submit"> - you are binding an event to your click on the button, and another event to the submit of the form, that happens when... well, when you click on the button. This maybe would work with some setup, but wasn't working, so I called the addItem from the save.
localStorage.setItem("stored_contacts", self.contacts); - you are trying to store an array of very complex objects (the contacts), each one full of several other complex objects (the observables) inside localStorage. localStorage, though, only stores strings. So you have to convert your objects to JSON. ko.toJSON is the way to go. More at the docs.
Edit:
This is a working JSFiddle with the saving part. I don't know how does JSFiddle handles the localStorage, but as I told you in the comments on my code in the original answer, your load function is wrong and will have to read the string from the localStorage, parse it to JSON (with JSON.parse(string)) and construct the appropriate objects using your constructor function (Contact). This is pretty easy and you can do by yourself.
Edit 2:
The load function should be something like this (haven't tested):
self.load = function(){
var contactsJSON = localStorage.getItem("stored_contacts"); // a string
var loadedContacts = JSON.parse(contactsJSON); // an array
self.contacts = ko.observableArray(); // an observableArray
for (var i in loadedContacts) {
var loadedContact = loadedContacts[i]; // an object
var newContact = new Contact(/* pass the parameters from loadedContact*/); // a Contact object
self.contacts.push(newContact);
}
}

How to get a random value from a Fixture Data in Ember

I'm playing with a sample Ember app that shows all the data stored in a Fixture, and finally tries to show a random data from the fixture.
Complete Demo here: http://jsbin.com/ifatot/2/edit
Everything works fine, however, I'm not able to get a random index out of the Ember Data. I'm trying to find its length and grab the random index but I believe the length is always coming up as 0, even though I have data in there.
The function looks like this:
App.ThoughtsController = Ember.ArrayController.extend({
randomMessage: function() {
var thoughts = this.get('model');
var len = thoughts.get('length');
var randomThought = (Math.floor(Math.random()*len));
return thoughts.objectAt(randomThought);
}.property('model')
});
You should add the length property as another dependent on the randomMessage computed property. This will allow the content to have finished resolving and have a length.
randomMessage: function() {
var len = this.get('length');
var randomThought = (Math.floor(Math.random()*len));
return this.objectAt(randomThought);
}.property('model', 'length')
Here's an updated jsbin.

Categories

Resources