Making an Array Variable Global in JavaScript - javascript

I'm setting a an array variable to 0 on load of my javascript.
var postArray= new Array();
However, I used this array to hold my objects that I retrieve from localStorage. It works when I upload more blog posts that get entered into localStorage and displays. However, after I refresh the page this is called again as is an empty array and say I go to enter my 3rd blog post after i've refreshed, my localStorage is set to only having the contents of my postArray. Therefore, I'm clearing out my localStorage when I dont want to.
if you throw it into an if statement, postArray is undefined.
if (localStorage.getItem("posts") === null) {
var postArray = new Array();
}
I'm trying to make the postArray global at the start yet only create a new array when localStorage is empty.

You should just get the content from the localStorage, and if it's empty, then return an empty array.
For example.
var postArray= getPosts();
function getPosts() {
var posts = localStorage.getItem("posts");
return posts ? JSON.parse(posts) : [];
}

i think you should use document coockie instead of array !!
when page is load read the cookie content if it's empty "localStorage" then store the "whatEver you want" value on its ! this is better than arrays

Related

How can I add elements to arrays without overwriting them?

I have an issue with saving items into an array in JavaScript/Next.js.
At the beginning I have an empty array. Then a session is started, and I check if the session is empty or not. If it is empty, I write a response of a get-request into a variable. At the same time I also write the response of the get request into localstorage.
Basically I now want to write the value of localstorage into the array with the push-method.
In the next step my program should realize, that the session is not empty anymore and now the new value of the get-request should be stored into localstorage and at the same time it should be added as a new element of the variable. The old elements of the array should not be overwritten. I have now tried a couple of things, but I could not get it to work.
Does anybody have a hint for me, how to realize this problem? I would be very thankful, if anybody could help me on this one 😊
api.get('products?include=' + mainId, addOrViewCartConfig).then((response) => {
if (isEmpty(storedSession)) {
storeSession(response.data[0].id);
localStorage.setItem('ID', response.data[0].id);
var localCart = [];
};
if (!localCart.indexOf(parseInt(localStorage.getItem('ID')))) {
localCart.push(parseInt(localStorage.getItem('ID')));
} else {
alert('The item you are trying to add is already in your cart!');
return false;
}
viewCart();
}).catch((error) => {
console.log('apiError');
});

Todo List with JavaScript and make remain on browser even after you refresh

I built a Todolist with JavaScript its working fine but I want my Todo-items to remain on the browser even if I refresh till I delete it. What can I do?
There are 2 ways to go about this
The common approach - get a backend service up and running, then store it in a database so that it can be fetched anytime from any device.
The browser only approach - If you are looking for a simple enough approach, you may use the localStorage API and implement localStorage.setItem(), localStorage.getItem() and localStorage.removeItem() methods to save your todos locally on the users machine. Do note that this data can be cleared by the user.
To know more about when localStorage is cleared, refer this When is localStorage cleared?
This solution uses LocalStorage to persist data across browser reloads.
Refer to in-code comments for guidance, particularly about tracking the state of your data in JavaScript, and syncing that state with both the UI and the persistent (stored) data.
Limitations:
The "ToDo" items in this demo have only a single property, a 'description'.
The UI only allows adding items (by typing a description and tabbing
or clicking out of the input).
The code runs correctly in Chrome, although NOT in the Stack Overflow snippet due to sandboxing.
<h3>Todo</h3>
<input id="newitem" />
<div id="list"></div>
<script>
// Names HTML elements, calls `makeAndAddNewItem` when input changes
const
newItemInput = document.getElementById("newitem"),
listDiv = document.getElementById("list");
newItemInput.addEventListener("change", makeAndAddNewItem);
// `tempList` is an array containing all our list items,
// serving as the Source of Truth for the state of our data.
// When it changes, we should update the page and the stored list
//
// On page load, we retrieve data from storage and update the page
const tempList = getListFromStorage();
showListOnPage(tempList);
function getListFromStorage(){ // Called on page load
// Gets the storedList (if any), converts it to an array
// and returns the array (or returns an empty array)
const storedList = localStorage.getItem("list");
const list = storedList ? JSON.parse(storedList) : [];
return list;
}
function showListOnPage(tempList){ // Called on page load
// Loops through the tempList array and adds each item to the page
for(let currentItem of tempList){
showItemOnPage(currentItem);
}
}
function showItemOnPage(item){ // Used on load and for new items
// Appends to the listDiv a new `p` element, whose content
// is the value of the `description` property of the item
let
descriptionNode = document.createTextNode(item.description),
newParagraph = document.createElement("p");
newParagraph.appendChild(descriptionNode);
listDiv.appendChild(newParagraph);
}
function makeAndAddNewItem(event){ // eventListener for new items
// Makes a `newItem` object whose `description` property
// comes from the value of the `newItemInput` element
// Adds the new item to the page and to the tempList
// Replaces the stored list, using the newly changed tempList
const newItem = {};
newItem.description = newItemInput.value;
newItemInput.value = ""; // Clears input
tempList.push(newItem); // Updates list
showItemOnPage(newItem); // Updates page
updateLocalStorage(tempList); // Updates storage
}
function updateLocalStorage(){ // Called when tempList changes
// Converts tempList (array) to a string to update localStorage.list
const listToStore = JSON.stringify(tempList);
localStorage.setItem("list", listToStore);
}
</script>

Keep array data on page load

I am trying to keep values in my array on different pages (Wordpress), I'm trying do this via global array but it doesn't seem to work. On "page-1" I am filling the array with data, the same script is loading when I click "page-2". I would be grateful if you point how to fix my problem.
var myArray = new Array();
// Here is issue my myArray with data becomes empty after second load
myArray = {
tablica: []
};
jQuery(document).ready(function(){
// need my array over here
});
It will again reinitialize on next page. You can use local storage for get value from first page to another page.
Unless your app is a spa, a new html page is loaded on navigation. Therefore your JS is re initialise. Global variable does not persist on navigation.
Use local storage, session storage or a server side solution.

Set data from localStorage when user is connected

I have been working on a save file for my game. The save file IS working, and console.log displays proper values:
function saveGame(){
localStorage.setItem('game', JSON.stringify(game));
}
function loadGame(){
var retrievedObject = localStorage.getItem('game');
console.log('retrievedObject: ', JSON.parse(retrievedObject));
}
Image of the logs: https://s28.postimg.org/bslusmagt/Untitled.png
I'm still new to all this as I have started learning JS couple of months ago. Right now my guess is that when the page is loaded, I'm supposed to set all these values. Trying the next thing i get "null" in console.log
console.log(JSON.parse(localStorage.getItem('game.plutonium')));
I thought values could be set something like:
game.plutonium = localStorage.getItem('game.plutonium');
But it doesn't work. Whats the trick here?
Here is my full JS code, just in case: http://pastebin.com/yM2wz410
Values are defined from line 1, and save / load file is on the line 350-356.
Why doesn't my method work?
function saveGame(){
var savefile = JSON.stringify(game);
localStorage.setItem("game", savefile);
}
function loadGame(){
var savefile = localStorage.getItem("game");
if (savefile === null) {
return;
}
game = JSON.parse(savefile);
}
Method above seems to have completely solved the problem. Thanks :)
JSON.stringify() changes the object you give it into a string (which can be stored very easily). But: you can't navigate that string anymore via string.key
To translate that json string back into a object (that can be navigated again), you need to use JSON.parse().
Your problem above is, that you store the whole object (as json) into the storage with key game and then try to get the item game.plutonium from the storage. Note that you didn't save anything as game.plutonium.
You need to first fetch the whole json string via localStorage.getItem('game'), then parse the string back to an object and only then you can navigate over it again like game.plutonium.
var game = JSON.parse(localStorage.getItem('game'))
var plutonium = game.plutonium;

Create object and add to array of pointers - always replaces existing array

I have probably misunderstood the documentation somehow but cannot figure this out.
What I want to do, is to be able to create a new ClientContact and save it to an array of pointers called contacts in Clients table.
This is the relevant code:
var Client = Parse.Object.extend("Client");
var selectedClient = new Client();
// sets the objectId based on URL params
selectedClient.id = $routeSegment.$routeParams.id;
var ClientContact = Parse.Object.extend("ClientContact");
var contact = new ClientContact();
contact.set('name', 'test');
contact.set('desc', 'some description');
contact.set('phoneNumber', '123');
selectedClient.add('contacts', contact);
selectedClient.save().then(function() {
console.log('saved');
}, function(error) {
console.error(error);
});
As expected, the contact is automatically saved and added to contacts when the selectedClient is saved.
But if I run the same code again (in the testing this means refreshing the page), a new ClientContact is saved but it replaces the contacts array entirely.
That is, only the most recent ClientContact is associated to the Client, any new additions replaces the array, leaving only one pointer.
I hope there is an obvious an easy fix that I have simply failed to spot.
Ok seems I have located the problem.
I was assuming that array operations on an object was independant on the local representation.
What I did above was to construct an object based on a known objectId:
var Client = Parse.Object.extend("Client");
var selectedClient = new Client();
// sets the objectId based on URL params
selectedClient.id = $routeSegment.$routeParams.id;
Turns out that array operations like add and remove are performed based on the local information. So doing the above construction leaves my array, in the selectedClient object, empty at each page refresh. This was the cause of my array being replaced with a new single valued array.
In short, one should fetch an object before performing array operations it seems.
The reason for the construction above was to avoid having to re-query the Client object when navigating around an AngularJS based webpage. The solution was fortunately simple: loading the Client object once in a parent scope.
This moves outside the scope of the question. Just wanted to mention that as well.

Categories

Resources