I wanted to save data in local storage in form of array.
the first item is adding successfully but when i try to ad second item it replace item 1
this is my script file
function store(title, description) {
let titl = JSON.parse(localStorage.getItem("titl"));
let descriptio = JSON.parse(localStorage.getItem("descriptio"));
if (titl == null) {
t = [title];
localStorage.setItem("titl", JSON.stringify(t));
} else {
t = [title]
titl.push(t);
}
if (descriptio == null) {
d = [description];
localStorage.setItem("descriptio", JSON.stringify(d));
} else {
d = [description];
titl.push(d);
}
}
you dont update localstorage for the second values, and your pushing an array with a value onto an array (i think you just want to push a value onto the array)?
I think something like this is what your trying to acheive?
function store(title, description) {
// load the existing values (default to an empty array if not exist)
let _title = JSON.parse(localStorage.getItem("title") || "[]")
let _description = JSON.parse(localStorage.getItem("description") || "[]")
// add the new items
_title.push(title)
_description.push(description)
// update stored values
localStorage.setItem("title", JSON.stringify(_title)
localStorage.setItem("description", JSON.stringify(_description)
}
Related
just have a question about how to push onto an array to ultimately store in the localstorage. I have the below code:
const handleSelectLayouts = (layout) => {
const layoutsArray = [];
layoutsArray.includes(layout)
? layoutsArray.filter((str) => str !== layout)
: layoutsArray.push(layout);
localStorage.setItem('layouts', JSON.stringify([...layoutsArray]));
console.log(layoutsArray)
}
I see it in localstorage, however, it only has one item at a time. In the code, I am trying to push onto an array. Not just have whatever is the most recent item inside the array alone. Anyone see anything odd here?
You need to retrieve the previously stored layoutsArray from the local storage
const handleSelectLayouts = (layout) => {
let layoutsArray = JSON.parse(localStorage.getItem('layouts')) || [];
if (layoutsArray.includes(layout)) {
layoutsArray = layoutsArray.filter((str) => str !== layout);
} else {
layoutsArray.push(layout);
}
localStorage.setItem('layouts', JSON.stringify(layoutsArray));
console.log(layoutsArray)
};
You are defining a new layoutsArray every time the function is called
const layoutsArray = [];
If you want to add to the array which is already in localStorage then try this
const layoutsArray = JSON.parse(localStorage.getItem('layouts')) || [];
so basically i want to make a phone contacts app, and i try to save the saved contact to local storage
so this is the function when the save button clicked
saveContact(name, number){
//To check if the name input or phone input is not blank
if(nameInput.value == '' || phoneInput.value == ''){
info.style.display = 'block'
}
const firstLetter = name[0].toUpperCase()
const getContact = localStorage.getItem(firstLetter)
const storedObject = {
[name]:number
}
//If contact's first letter exists in localstorage
if (getContact){
const oldData = [JSON.parse(localStorage.getItem(firstLetter))]
oldData.push([storedObject])
const oldDataString = JSON.stringify(oldData)
localStorage.setItem(firstLetter, oldDataString)
const finalOldData = []
//i do a looping here to push each contact's object to a new array which is finalOldData
//but it doesn't work well. it doesn't actually add a new object to the array instead of replacing the old object with a new one
oldData.forEach(e => {
finalOldData.push(e[0])
})
const finalOldDataString = JSON.stringify(finalOldData)
localStorage.setItem(firstLetter, finalOldDataString)
}
//If contact's first letter doesn't exist in localstorage
else{
const storedObjectString = JSON.stringify([storedObject])
localStorage.setItem(firstLetter, storedObjectString)
this.clearSave()
}
}
so the issue is when i try to add a contact which its first letter exist in local storage and make it as a list
//and this is the result i want
Storage
A: "[{\"amber\":\"1242134\"},{\"annie\":\"123421\"}]"
length: 1
You can consider the code below, it is working as expected.
Changes
const oldData = [JSON.parse(localStorage.getItem(firstLetter))]
No need to put the result from JSON.parse into an array, it already is an array and also you can use the variable getContact instead of calling getItem again on localStorage.
oldData.push([storedObject])
No need to push an array into oldData, simply push storedObject.
I've removed the initial check for making testing easy, you can add it back.
function saveContact(name, number) {
if (!name || !number) {
return;
}
const firstLetter = name[0].toUpperCase();
const getContact = localStorage.getItem(firstLetter);
const storedObject = { [name]: number };
if (getContact) {
const oldData = JSON.parse(getContact);
oldData.push(storedObject);
const oldDataString = JSON.stringify(oldData);
localStorage.setItem(firstLetter, oldDataString);
} else {
const storedObjectString = JSON.stringify([storedObject]);
localStorage.setItem(firstLetter, storedObjectString);
}
}
I have to select few elements from UI and then need to store the id of each selected in the localstorage. When user will deselect it , then that value from localstorage should also be removed . for that which I did
#observable marks = JSON.parse(localStorage.getItem('marks')) || [];
#action handleChange = Mid => {
let getMarks = JSON.parse(localStorage.getItem('marks')) || [];
let foundIndex = getMarks.indexOf(Mid)
if (foundIndex > -1) {
remove(getMarks, id => id === Mid)
} else {
localStorage.setItem('marks', JSON.stringify([Mid]))
}
}
Here, localStorage adds the only recent value and while and also not getting set to the observable which I am using it to render .
How do I fix this ?
Thanks.
Updated fix
#action handleChange = Mid => {
let foundIndex = this.marks.indexOf(Mid)
if (foundIndex > -1) {
remove(this.marks, id => id === Mid)
localStorage.setItem('marks', JSON.stringify(this.marks))
} else {
this.marks.push(Mid)
localStorage.setItem('marks', JSON.stringify(this.Mid))
}
}
To add new item you want to push it into the existing array. Instead you are creating a new array with one element and ignoring anything that was previously stored
Change:
localStorage.setItem('marks', JSON.stringify([Mid]))
To
getMarks.push(Mid)
localStorage.setItem('marks', JSON.stringify(getMarks))
I want to add objects into a local storage array if they are not in it otherwise, increase the objects' quantity by 1. Here is my function:
function addToCart() {
let productsTable = localStorage.getItem("productList");
// Check if productsTable exists in local storage
if (productsTable === null){
// If not, initialize the array and add the current object
productsTable = [];
objetProduit.quantity ++;
productsTable.push(objetProduit);
}else{
// If yes, decode the array.
productsTable = JSON.parse(productsTable);
// check if the object is already in the array
if(productsTable.find(product => product.id !== objetProduit.id)){
//if not ==> add the object into the array
objetProduit.quantity ++;
productsTable.push(objetProduit);
}else if (productsTable.find(product => product.id == objetProduit.id)){
//if yes ==> just increase the value of the key quantity by 1
objetProduit.quantity ++;
}
}
// Encode the array.
productsTable = JSON.stringify(productsTable);
// Add the array back to LocalStorage.
localStorage.setItem("productList", productsTable);
The objetcs are instances of the class below :
class Appareil {
constructor(id,name,price,description,imageURL, quantity){
this.id = id;
this.name = name;
this.price = price;
this.description = description;
this.imageURL = imageURL;
this.quantity = quantity;
}
}
The array get initialized but items are not added in it nor is the quantity modified.
Avoid the following check condition:
if(productsTable.find(product => product.id !== objetProduit.id))
as it will return the first product's index which doesn't match in the array, so chances are there will be many products which will not be matching
Refer:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
Try:
function addToCart() {
let productsTable = localStorage.getItem("productList");
// Check if productsTable exists in local storage
if (!productsTable) {
// If not, initialize the array and add the current object
productsTable = [];
objetProduit.quantity++;
productsTable.push(objetProduit);
} else {
// If yes, decode the array.
productsTable = JSON.parse(productsTable);
// check if the object is already in the array
if (productsTable.find(product => product.id === objetProduit.id)) {
//if yes ==> just increase the value of the key quantity by 1
objetProduit.quantity++;
for (var i = 0; i < productsTable.length; i++) {
if (objetProduit.id === productsTable[i].id) { //look for match with id
productsTable[i].quantity++; //add
break; //exit loop
}
}
} else {
//if not ==> add the object into the array
objetProduit.quantity++;
productsTable.push(objetProduit);
}
}
// Encode the array.
productsTable = JSON.stringify(productsTable);
// Add the array back to LocalStorage.
localStorage.setItem("productList", productsTable);
}
i have 5 items in my page with 3 information. (for example, name and price and number )
i want when i click on them (for example item 1) for first time, create an object and save items information to localStorage and for another times increase the number of item in localstorage.
function() {
items.forEach(function(btn) {
btn.addEventListener('click', function(event) {
let exist = localStorage.getItem('name');
var name =
event.target.parentElement.parentElement.parentElement.parentElement.children[1].children[0].textContent;
localStorage.setItem('name', name);
var price =
event.target.parentElement.parentElement.parentElement.parentElement.children[1].children[2].textContent;
localStorage.setItem('price', price);
var number = localStorage.getItem('number');
number = parseInt(number);
if (number) {
localStorage.setItem('number', number + 1);
} else {
localStorage.setItem('number', 1)
}
});
});
})();
its my code, but when i click on any item, previeos details in localstorage will be lost and information of new item replaced.
how i can resolve it?
When you are calling localStorage.setItem('name', name) you are overwriting the previous value of name. To store all names, prices, and numbers you have to use array. But, localStorage supports nothing but string. So before writing, you have to convert the array to a string, and upon reading you have to revert the string back to an array.
function() {
items.forEach(function(btn) {
btn.addEventListener('click', function(event) {
let names = localStorage.getItem('name');
const exists = !!names;
names = exists ? JSON.parse(names) : [];
let prices = exists ? JSON.parse(localStorage.getItem('price')): [];
let numbers = exists ? JSON.parse(localStorage.getItem('number')) : [];
var name =
event.target.parentElement.parentElement.parentElement.parentElement.children[1].children[0].textContent;
const nI = names.indexOf(name);
if (nI === -1) {
names.push(name);
localStorage.setItem('name', JSON.stringify(names));
var price =
event.target.parentElement.parentElement.parentElement.parentElement.children[1].children[2].textContent;
prices.push(price);
localStorage.setItem('price', JSON.stringify(prices));
numbers.push(1);
} else {
// else they are already in localStorage, just increase number
numbers[nI]++;
}
localStorage.setItem('number', JSON.stringify(numbers));
});
});
})();