JSON string not loading data into local storage - javascript

I am building an application that will load bus schedules into local storage, then based on a search term provides the stops on the bus schedule. It works by clicking the load button and sending the information to local storage. Then you search a route name, and the stops information will be displayed into results. When I run in a browser my data is not loading into local storage when I press load.
<html>
<head>
<script type="text/javascript">
/**
* A JSON string that holds data. There is no problem with the JSON string
* #type {String}
*/
var busSchd = '{"Routes": [{"routeName": "Milledge","stops":[{"Stop 1":"Main Library","Stop 2":"Clarke Central","Stop 3":"Five Points South","Stop 4":"Five Points North","Stop 5":"Waddell"}]},{"routeName": "Orbit","stops":[{"Stop 1":"Main Library","Stop 2":"Clarke Central","Stop 3":"Five Points South","Stop 4":"Five Points North","Stop 5":"Waddell"}]},{"routeName": "East West","stops":[{"Stop 1":"East Campus Deck","Stop 2":"Creswell Hall","Stop 3":"Hull St Deck","Stop 4":"Main Library","Stop 5":"Joe Frank Harris"}]}]}';
const load = () => {
let data = JSON.parse(busSchd);
console.log("a");
for (var i = 0; i < data.Routes.len;)
{
let route = data.Routes[i];
let routeStr = route.routeName;
localStorage.set(routeStr, JSON.stringify(route.stops));
}
};
const clicked = () => {
var search = document.getElementById("search");
var results = localStorage.getItem("search");
if (results === null) {
document.getElementById("result").innerHTML = "<b>There are no results for that route name.</b>";
} else {
var stops = results;
var output = '';
for (var key in stops[0]) {
output = output + '<b>' + key + '</b> : ' + stops[0][key] + '<br>';
}
document.getElementById("result").innerHTML = output;
}
};
</script>
</head>
<body>
<input type="button" value="Load Route Data" id="load" onclick="load();">
<br>
<br>
<input type="text" id="search"><input type="button" value="Find Route" id="submit" onclick="clicked();"><br>
<br><br>
<div id="result">
</div>
</body>
</html>

There were a few mistakes within your code which prevented you from saving to localStorage. Here are some pointers.
Use localStorage.setItem() to save and localStorage.getItem() to retrieve data.
There's no need for creating a localStorage item for each bus route. LocalStorage can handle quite some data, depending on the browser and user browser settings. See What is the max size of localStorage values? for more info.
I'd simplify your data structure. Why put stops data into an array and then into an object? I've simplified this in my example.
When iterating over items use for (var i = 0; i < data.Routes.length; i++) { // your code here } another alternative is to user .map when iterating over items within an array.
Here's how to load data and save it to localStorage and into the app.
let BusSchdDataFromLocalStorage = [];
const load = () => {
// access localStorage and save the result in data
let data = JSON.parse(localStorage.getItem('routesInfo'));
if (data === null) {
// if no data is present, save InitialBusScheduleData to localStorage
localStorage.setItem('routesInfo', JSON.stringify(InitialBusScheduleData));
}
// Now that data is present in localStorage, read it.
data = JSON.parse(localStorage.getItem('routesInfo'));
if (data.Routes.length > 0) {
// if routes are present, save its data to a global var in our app
BusSchdDataFromLocalStorage = data;
statusEl.innerHTML = 'localStorage data present'
} else {
statusEl.innerHTML = 'localStorage data absent'
}
};
Here's how the search part works.
const search = () => {
const searchString = document.querySelector('#search').value;
// data from localStorage is present in the variable below
const routes = BusSchdDataFromLocalStorage.Routes;
// Filter route data based on the search input.
const busStopInfo = routes.reduce((stops, route) => {
return (route.routeName.toLowerCase() === searchString.toLowerCase()) ? route.stops : stops;
}, []);
const stops = Object.keys(busStopInfo);
// map over the stops and return the html structure with the stop number and the value
const results = stops
.map((stop) => '<div>' + stop + ' - ' + busStopInfo[stop] + '</div>')
.join('');
// add the html result to the result div.
resultEl.innerHTML = results.length > 0 ? results : 'No route found with that name.';
};
If you'd like to see the code in action. Here's a JSFiddle.

Related

Add items to basket and store in localStorage with JavaScript

I want to create an action for the button to be able to add items to the basket and keep data in localStorage. I'm struggling with push items when the basket has already more than one item inside. I can easily increase the quantity of existing items if an ID is same but can't add new items. Data I'm getting from JSON file. JSON contains only five unique IDs. Below part of my code.
AddBtn.addEventListener('click', function (add) { //Add item to when click AddBtn localStorage
add.preventDefault() // Avoid default action.
const basket = JSON.parse(localStorage.getItem('basket')); // Parse data from localstorage
let elementimageUrl = element.imageUrl; // element.imageUrl is a part of backend data received from JSON file
let elementId = element._id; // element._id is a part of backend data received from JSON file
let elementName = element.name; // element.name is a part of backend data received from JSON file
let elementPrice = element.price; // element.price is a part of backend data received from JSON file
let elementQuantity = 1;
if(basket === undefined || basket.length > 4 ){
//Existing data block in local storage
basket.forEach(product => {
if (product.elementId === elementId) {
product.elementQuantity++
console.log('increase');
}
});
} else{
//Non Exist data block in local storage
basket.push({elementId, elementName, elementPrice, elementQuantity, elementimageUrl}); // Push not existing data to localstorage
console.log('add')
window.location.reload();
}
localStorage.setItem('basket', JSON.stringify(basket));
});
Here is a working solution for your problem.
AddBtn.addEventListener('click', function (add) { //Add item to when click AddBtn localStorage
add.preventDefault() // Avoid default action.
let basket = JSON.parse(localStorage.getItem('basket')); // Parse data from localstorage
let elementimageUrl = element.imageUrl; // element.imageUrl is a part of backend data received from JSON file
let elementId = element._id; // element._id is a part of backend data received from JSON file
let elementName = element.name; // element.name is a part of backend data received from JSON file
let elementPrice = element.price; // element.price is a part of backend data received from JSON file
let elementQuantity = 1;
if (!basket) {
basket = [];
}
// find the index of the item if already in basket
const itemIndexInBasket = basket.findIndex(basketEntry => basketEntry.elementId === elementId);
if (itemIndexInBasket !== -1) {
basket[itemIndexInBasket].elementQuantity++;
} else {
basket.push({elementId, elementName, elementPrice, elementQuantity, elementimageUrl}); // Push not existing data to localstorage
}
localStorage.setItem('basket', JSON.stringify(basket));
});
Can you share a jsfiddle link with dummy values for variables? It will be a lot easier to debug.
Seeing the above explanation that you are facing a problem with push items I assumed this below data and it is working.
const basket = [{abc:"1"},{abcs:'3'}];
let elementimageUrl = 'abc';
let elementId = 1;
let elementName = 'a';
let elementPrice = 10;
let elementQuantity = 1;
basket.push({elementId, elementName, elementPrice, elementQuantity, elementimageUrl});
console.log('add')
console.log(basket);
localStorage.setItem('basket', JSON.stringify(basket));

Writing from JSON to HTML via JavaScript

Okay so I have a website that needs to display some data from a JSON file. The file contains different places in Norway with their name (Halden), state number (kommunenummer), number of men (menn) and number of women (kvinner).
I need to write some code that displays every name, state number and the total population of that place (which is the most recent measurement of men + women)
The JSON data looks like this:
"elementer": {
"Halden": {
"kommunenummer": "0101",
"Menn": {
"2016": 15306,
"2017": 15473,
"2018": 15620
},
"Kvinner": {
"2016": 15238,
"2017": 15317,
"2018": 15417
}
}
And so on... The JSON file has a lot of these. The attribute "elementer" is where all the data is stored, so when I open "elementer" in my browser console, I get all of the states listed.
So this is where I need the JSON data to be displayed;
<div id="visOversikt">
<ul>
<li>hei</li>
</ul>
</div>
My JavaScript looks like this:
function load(url, objekt){
var request = new XMLHttpRequest()
request.open('GET', url, true)
request.onreadystatechange = function () {
if(request.readyState === 4 && request.status === 200) {
console.log("Data er lastet inn vellykket...");
}
}
request.onload = function() {
// Begin accessing JSON data here
objekt.data = JSON.parse(this.response)
}
request.send()
}
var befolkning = {
}
load("http://wildboy.uib.no/~tpe056/folk/104857.json", befolkning)
function getNames(data) {
for (var variable in data) {
console.log(variable)
}
function displayOversikt() {
}
}
The function displayOversikt() is where I thought I could write the code to display the data. If anyone can help I would appreciate it. Say I write getNames(befolkning.data.elementer) in the console, I listed all the state names (if it is of any help).
I have done it in simple jquery.
Your html
<html>
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="JsonView.js"></script>
</head>
<body>
<div id="visOversikt">
<ul></ul>
</div>
</body>
</html>
Your jquery(JsonView.js) would be
$(document).ready(function(){
$.getJSON("http://wildboy.uib.no/~tpe056/folk/104857.json", function(json) {
$.each(json['elementer'],function(key,value){
var stateName = key;
var kommunenummer = value['kommunenummer'];
var MennValue = value['Menn']['2018'];
var FemaleValue = value['Kvinner']['2018'];
var addition = MennValue + FemaleValue;
var li = '<li>'+stateName+', '+kommunenummer+', '+addition+'</li>'
$("#visOversikt ul").append(li)
});
});
})
First of all, I would suggest looking at the fetch API. It's a real improvement on the older AJAX style you use.
Then, I would break the problem down into three phases:
Use fetch to get the data
Restructure the data to include exactly what you want
Format each element of that data into HTML
Here's one way that might look:
const output = document.getElementById('output')
const structureTownData = ([name, {kommunenummer, Menn, Kvinner}]) => ({
name,
kommunenummer,
pop: Number(Menn['2018']) + Number(Kvinner['2018'])
})
const formatOutput = ({name, kommunenummer, pop}) => {
const el = document.createTextNode(`${name} (#${kommunenummer}): ${pop}`)
const li = document.createElement('li')
li.appendChild(el);
output.appendChild(li)
}
fetch("http://wildboy.uib.no/~tpe056/folk/104857.json")
.then(resp => resp.json())
.then(({elementer}) => Object.entries(elementer).map(structureTownData))
.then(towns => towns.forEach(formatOutput))
<ul id="output"></ul>
<script>
data = {"elementer":{"Halden":{"kommunenummer":"0101","Menn":{"2016":15306,"2017":15473,"2018":15620},"Kvinner":{"2016":15238,"2017":15317,"2018":15417}},"Oslo kommune":{"kommunenummer":"0301","Menn":{"2016":328424,"2017":332578,"2018":335806},"Kvinner":{"2016":329966,"2017":334181,"2018":337663}}}}
// fake fetch for testing
const fetch = (url) => Promise.resolve(({json: () => data}))
</script>
There are plenty of alternative ways to create your HTML. And you'd have to decide on the exact format you want. Here I just use an unordered list with elements that look like Halden (#0101): 31037.
Already answered here https://stackoverflow.com/a/20135028/5525384
const div = document.getElementById('visOversikt');
function makeList(jsonObject, listElement){
for(var i in jsonObject){
var newLI = document.createElement('li');
if (jsonObject[i] instanceof Array){
newLI.innerHTML=i;
}
else if (jsonObject[i] instanceof Object){
newLI.innerHTML=i;
}
else {
newLI.innerHTML=i+': '+jsonObject[i];
}
listElement.appendChild(newLI)
if (jsonObject[i] instanceof Array || jsonObject[i] instanceof Object){
var newUL = document.createElement('ul');
listElement.appendChild(newUL);
makeList(jsonObject[i],newUL);
}
}
}
makeList(jsonObject, div);
try to use <template> and split data and view
let data = {"elementer":{"Halden":{"kommunenummer":"0101","Menn":{"2016":15306,"2017":15473,"2018":15620},"Kvinner":{"2016":15238,"2017":15317,"2018":15417}},"Moss":{"kommunenummer":"0104","Menn":{"2016":16000,"2017":16085,"2018":16124},"Kvinner":{"2016":16182,"2017":16322,"2018":16464}}}}
function displayOversikt(data) {
let inject = (s,o)=>s.replace(/\${(.*?)}/g,(x,g)=>o[g]); // helper which inject object fields into string in ${filedname}
// Prepare data
let dd= Object.entries(data.elementer).map(([x, y]) => {
let year = Object.keys(y.Menn).sort((a,b)=>+b-a)[0]; // last year
return {
population: y.Menn[year] + y.Kvinner[year],
num: y.kommunenummer,
name: x,
}});
// Read templae string
let t=item.innerHTML;
// Bind data to template and write in content element
content.innerHTML = dd.map(x=> inject(t,x)).join('');
}
displayOversikt(data);
<div ><ul id="content"></ul></div>
<template id="item">
<li>${name}, ${num}, ${population}</li>
</template>

Having issues with w/auto-populating last search result on my html form page when hitting refresh, using only javascript and local storage

I want to rerun the search or populate the results as if the user never left.
So I visit the page, search for cats and get some results based on cats. I close the tab, come back later, and rather than find myself on a fresh page that has no results, I’m provided with the results from my last search. I am only allowed to use Javascript and local storage to achieve this. Here is my JS file:
var search = document.getElementById('searchTerm');
if(!localStorage.getItem('input')) {
populateStorage();
}
// To set the event to listen to
const form = document.querySelector('.js-search-form');
// To listen when user hits submit or press enter
form.addEventListener('submit', (e) => {
// Start of the query string
const base = `https://api.themoviedb.org/3/search/movie?include_adult=false&page=1&`;
// Extension of the query string
const searchTerm = document.querySelector('#searchTerm').value;
const language = `en-US&`;
const api_key = `7ab3cb18b4ad4a07bbd8bb01acfa7091`;
// The complete build of the url
const url = `${base}query=${searchTerm}&language=${language}api_key=${api_key}`;
// The get method
const option = {
method: 'GET'
}
// Stops the default action
e.preventDefault()
fetch(url)
//Parse data
.then( response => {
if (response.ok) {
return response.json()
} else {
throw response
}
})
// Do something with data
.then( data => {
console.log(data)
// Output results
let resultElement = '';
if(data.results.length > 1) {
resultElement += `
<h2><span>Results for ${searchTerm}</span></h2>
<section class="js-search-results clearfix">
`;
if(data.results) {
data.results.forEach(function(results){
resultElement += `<article class="item">
<div class="container">
<img src="https://image.tmdb.org/t/p/w500${results.poster_path}"/>
<div class="content">`;
if(results.title.length > 17) {
resultElement += `<h3>${results.title.substr(0,17)}...</h3>`;
} else {
resultElement += `<h3>${results.title}</h3>`;
}
resultElement += `<p>Released: ${results.release_date}</p>`;
resultElement += `</div>
</div>
</article>`;
});
resultElement += `</section>`;
populateStorage()
} else {
resultElement += '<p class="no-results">No results</p>';
}
document.querySelector('.js-search-results').innerHTML = resultElement;
}
})
.catch(err => {
console.log(err)
})
})
function populateStorage() {
localStorage.setItem('searchTerm', document.getElementById('searchTerm').value);
}
EDIT -
You are calling localStorage.getItem('input'); but you are saving the local storage item as searchTerm please make these names consistent with one another
you either need to change localStorage.getItem('input')
TO
localStorage.getItem('searchTerm');
OR
change localStorage.setItem('searchTerm', document.getElementById('searchTerm').value)
TO
localStorage.setItem('input', document.getElementById('searchTerm').value)
-Edit-
Assuming that this is wrapped in a document ready function, update your initial check of storage to look like this...
var search = document.getElementById('searchTerm');
//This assumes that you corrected your getItem to reference 'searchTerm'
if(!localStorage.getItem('searchTerm')) {
populateStorage();
}
else {
search.value = localStorage.getItem('searchTerm');
}
Your code never makes a call to actually populate that field so this should fix that.

How to add item to local storage

I am creating a song book app with 'add to favorite' button. i have song1.html song2.html and favorite.html.
in song1.html, when add to favorite button is clicked. i am storing the link to that song in local storage.
This is my song1.html
<!DOCTYPE html>
<html>
<body>
<button onclick="mySongOne()">add to favorite</button>
<script>
function mySongOne() {
localStorage.setItem("favsong", "<a href='https://www.song1.com'><h1>song1</h1></a>");
}
</script>
</body>
</html>
in song2.html, when add to favorite button is clicked. i am storing the link of the second song in local storage.
song2.html
<!DOCTYPE html>
<html>
<body>
<button onclick="mySongTwo()">add to favorite</button>
<script>
function mySongTwo() {
localStorage.setItem("favsong", "<a href='https://song2.com'><h1>song2</h1></a>");
}
</script>
</body>
</html>
now i have a favorite.html for listing my favourite songs. and favourite.html will retrieve the links that i stored in local storage.
favorite.html
<!DOCTYPE html>
<html>
<body onload="myFunction()">
<div id="result"></div>
<script>
function myFunction() {
document.getElementById("result").innerHTML = localStorage.getItem("favsong");
}
</script>
</body>
</html>
Now i want to show both song 1 and song 2 in favorite.html.
but only song 2 is displayed in favourite.html. How to accomplish this.
Store list in javascript Array.
You need to either use different keys or store multiple strings in array and then JSON.stringify that to save in localStorage.
Similary when you get the same string from localStorage then convert it into object using JSON.parse.
<!DOCTYPE html>
<html>
<body>
<div id="result"></div>
<script>
// Check browser support
if (typeof(Storage) !== "undefined") {
// Store
let list = [];
list.push("<h1>John<h1>");
list.push("<h2>David<h2>");
localStorage.setItem("list", JSON.stringify(list));
// Retrieve
document.getElementById("result").innerHTML = JSON.parse(localStorage.getItem("list"));
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
</script>
</body>
</html>
When using localStorage, you can only have one item per key. localStorage allows you to store string-data as the value, thus we can use JSON.
You can serialize an array of items you want to add and then append them to the key inside of localStorage.
References:
JSON.stringify()
JSON.parse()
localStorage
JSFiddle. StackOverflow doesn't allow localStorage so I hosted my code there.
Code:
let items = ['<h1>John<h1>', '<h2>David<h2>', '<h3>Mary<h3>', '<h4>Bob<h4>'];
// Stringify the array and store it
localStorage.setItem("list", JSON.stringify(items));
// Parse the stringified array back from localStorage
let itemsRetrieved = JSON.parse(localStorage.getItem('list'));
// Get div with .list class
let div = document.querySelector('.list');
// Iterate retrieved array and append items
itemsRetrieved.forEach(item => {
div.innerHTML += item;
});
// Add an item
itemsRetrieved.push('<span style="color: red;">Dylan</span>');
// Stringify the new array and overwrite the key
localStorage.setItem("list", JSON.stringify(itemsRetrieved));
Code [For those who love encapsulation]:
let items = ['<h1>John<h1>', '<h2>David<h2>', '<h3>Mary<h3>', '<h4>Bob<h4>'];
// Stringify the array and store it [Initial]
localStorage.setItem("list", JSON.stringify(items));
// Returns parsed array
function getData(key) {
return JSON.parse(localStorage.getItem(key));
}
// Returns new array
function addData(key, item) {
// Get current array
let currentData = getData(key);
// Add an item
currentData.push(item);
// Stringify the new array and overwrite the key
localStorage.setItem(key, JSON.stringify(currentData));
return currentData;
}
// Parse the stringified array back from localStorage
let itemsRetrieved = getData('list');
// Get div with .list class
let div = document.querySelector('.list');
// Add an item
itemsRetrieved = addData('list', '<span style="color: red;">Dylan</span>');
// Iterate retrieved array and append items
itemsRetrieved.forEach(item => {
div.innerHTML += item;
});
If you really need to append data to the same LocalStorage key, there is no built-in append function.
However, you can use a custom function, for instance the one proposed in this answer: https://stackoverflow.com/a/7680123/2446264, and get the following code to do what you want:
<!DOCTYPE html>
<html>
<body>
<div id="result"></div>
<script>
// Check browser support
if (typeof(Storage) !== "undefined") {
// Store
localStorage.setItem("list", "<h1>John<h1>");
appendToStorage("list", "<h2>David<h2>");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("list");
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
function appendToStorage(name, data){
var old = localStorage.getItem(name);
if(old === null) old = "";
localStorage.setItem(name, old + data);
}
</script>
</body>
</html>
Basically, you'll need to store those data as a list of strings (or use different keys 'list1', 'list2' etc...).
So, when you are putting your value into the local storage initially, you'll need to do something like this:
var initialValue = ['<h1>John<h1>']; // array of strings
// since Local Storage accepts only string values,
// you can store an array or any other object by using JSON.stringify function
localStorage.setItem('list', JSON.stringify(initialValue);
// updating local storage
var list = JSON.parse(localStorage.getItem('list');
list.push('<h2>David<h2>');
localStorage.setItem('list', JSON.stringify(list));
Then you can append those value by looping through the list.
var output = '';
for (var i = 0; i < list.length; i++) {
output = output + list[i];
}
document.getElementById("result").innerHTML = output;
What you are doing wrong:
localstorage doesn't store data types, but rather stores a string.
For instance, if you was to store an integer in a localstorage property, the data type would always be returned as a string.
Since you are attempting to store an array of values, you will need to create a CSV (comma-separated values) method.
var strLocalStorage = "John, Peter, Fred, Paul, Mary, Elizabeth";
You can the parse this into local storage using one of two methods
JSON (See example beneath)
SPLIT (variable.split(", ");
It is important you should be aware, Browsers set limitations of 5MB of data allocated between LocalStorage and SessionStorage.
This can cause problems when a large amount of data needs to be stored, in the event of your edited example, storing various URLs
What may be an alternative to your solution, would be to create CSV of favourite songs using your SQL Table's unique ID for the song table entry.
However, in the event your code is only using Front End languages such as HTML and JAVASCRIPT, then you may prefer to use IndexedDB
How to use Indexed DBs
This will allow you to create a local database that is accessible offline and allows you to recall and edit the values easier such as
LocalStorage Example:
var blLocalStorage = false;
function funInitiate(){
if (typeof(Storage) !== "undefined") {
console.log("localstorage detected on this browser");
blLocalStorage = true;
}else{
console.log("local storage is not supported by this browser, please update");
}
}
function funTestLocalStorage(){
var strLocalStorage = localStorage.getItem("FavSongs");
if(strLocalStorage === null){
return false;
}else{
return true;
}
}
function funGetSongFavorites(){
if(blLocalStorage){
if (funTestLocalStorage()){
var arrLocalStorage = JSON.parse(localStorage.getItem("FavSongs"));
var elOutput = document.querySelector("#result");
for(i = 0; i < arrLocalStorage.length; i++){
elOutput.innerHTML += "<br>" + arrLocalStorage[i]
}
}
}else{
console.log("No local storage - function funGetSongFavourites aborted");
}
}
function funAddFav(strURL){
if(blLocalStorage){
var strLocalStorage = localStorage.getItem(strURL);
if(strLocalStorage === null){
localStorage.setItem("FavSongs", strURL);
}else{
var arrList = JSON.parse(localStorage.getItem('FavSongs'));
arrList.push(strURL);
}
localStorage.setItem('FavSong', JSON.stringify(arrList));
console.log("Favourite Lists update: " + strURL);
}else{
console.log("No local storage - Function funAddFav aborted");
}
}
document.addEventListener("DOMContentLoaded", funInitiate, false);
<!DOCTYPE html>
<html>
<head>
<title>Webpage Title</title>
<script src="pathToJSScriptShownBeneath"></script>
</head>
<body>
<button onclick="funAddFav('http://youtube.com')">
Add to favorite
</button>
<div id="result"></div>
</body>
</html>
Indexed DB example
var songList = [
{ id: 1, artist: "2pac", title: "Dear Mama", URL: "https://www.youtube.com/watch?v=Mb1ZvUDvLDY" },
{ id: 2, artist: "Biggie Smalls", title: "Hypnotize", URL: "https://www.youtube.com/watch?v=glEiPXAYE-U" }
];
const dbName = "favSongs";
var request = indexedDB.open(dbName, songList.length);
request.onerror = function(event) {
console.log("An Error has occured, script will now exist";
return;
};
request.onupgradeneeded = function(event) {
var db = event.target.result;
var objectStore = db.createObjectStore("SongList", { keyPath: "id" });
// There can be multiple songs by 1 artist or band therefore this will
// declare this as a false unique entry, the sample applies for song titles
// some songs have the same title but performed by different artists.
objectStore.createIndex("artist", "artist", { unique: false });
objectStore.createIndex("title", "title", { unique: false });
// Song URLs will be unique, so we set this as a individually unique
objectStore.createIndex("URL", "URL", { unique: true });
// Use transaction oncomplete to make sure the objectStore creation is
// finished before adding data into it.
objectStore.transaction.oncomplete = function(event) {
// Store values in the newly created objectStore.
var customerObjectStore = db.transaction("favSongs", "readwrite").objectStore("SongList");
customerData.forEach(function(songList) {
customerObjectStore.add(songList);
});
};
};
// Retrieving Data:
var transaction = db.transaction(["favSongs"]);
var objectStore = transaction.objectStore("SongList");
var request = objectStore.get(2);
request.onerror = function(event) {
console.log("Entry doesnt exist of has been deleted");
};
request.onsuccess = function(event) {
var strArtist = request.result.artist;
var strTitle = request.result.title;
var strURL = request.result.URL;
};
// Deleting Data
var request = db.transaction(["favSongs"], "readwrite")
.objectStore("SongList")
.delete(1);
request.onsuccess = function(event) {
console.log ("Entry 1 has been deleted");
};
Add item: localStorage.name = 'Name'
Get item: let name = localStorage.name
Remove item: localStorage.removeItem('name')

Storing arrays in localStorage error

I have a bug in my code that only saves the last object in an array upon reload. I have a feeling that my addAccount() function is not saving or inserting data correctly. Everything else works correctly. In my console, it shows that the data is being inserted into the array, but when I refresh I only get the last object saved.
I'm not sure what to do.
// The list of accounts array.
var accountsArray = [];
function addAccount() {
// Take fields and put user data into varables.
var accountName = document.getElementById('accountName').value;
var accountBalance = document.getElementById('accountBalance').value;
var accountType = document.getElementById("accountType");
var accountTypeSelected = accountType.options[accountType.selectedIndex].text;
var accountCurrency = document.getElementById("accountCurrency");
var accountCurrencySelected = accountCurrency.options[accountCurrency.selectedIndex].text;
var temporaryObject = {
'accountName': accountName,
'accountBalance': accountBalance,
'accountTypeSelected': accountTypeSelected,
'accountCurrencySelected': accountCurrencySelected
};
accountsArray.push(temporaryObject);
console.log(accountsArray);
saveAccountData();
showAccountsArray();
}
function saveAccountData() {
localStorage.setItem('accountsArray', JSON.stringify(accountsArray));
}
function showAccountsArray() {
//var accountsLocalStorage = JSON.parse(localStorage['accountsArray']);
if (localStorage.getItem("accountsArray") === null) {
document.getElementById("getStarted").style.visibility="visible";
document.getElementById("balanceToolbarName").style.visibility="hidden";
document.getElementById("accountsMainList").style.visibility="hidden";
} else {
var accountsLocalStorage = JSON.parse(localStorage['accountsArray']);
console.log(accountsLocalStorage);
var accountInfo = '';
var i = 0;
while (i < accountsLocalStorage.length) {
accountInfo += '<li class="swipeout"><div class="swipeout-content item-content"><div class="item-inner"><div class="item-title">' + accountsLocalStorage[i].accountName + '</div><div class="item-after">$' + accountsLocalStorage[i].accountBalance + '</div></div></div><div class="swipeout-actions-left"><a href="#" class="action1">Clear</div><div class="swipeout-actions-right">Delete</div></a></li>';
document.getElementById("accountsList").innerHTML = accountInfo;
i++;
}
document.getElementById("getStarted").style.visibility="hidden";
document.getElementById("balanceToolbarName").style.visibility="visible";
document.getElementById("accountsMainList").style.visibility="visible";
}
}
*
all of your functions work correctly as tested by the link you've provided. When the page loads it successfully retrieves the data (if any) from the local storage and displays on the page. However, the global array variable accountsArray is populated with data retrieved from the local storage.
You need to repopulate the global array otherwise when you call saveAccountData it will save whatever the array holds which indeed overrides whatever you had in the local storage. To fix it, simply add add this code block...
$(function(){
var data = localStorage.getItem("accountsArray");
if(data != null)
accountsArray = JSON.parse(localStorage.getItem("accountsArray"));
});

Categories