If the value is exist in localstorage I want to replace it. When I try to do that existing value is still inserting.
addEntry = (e,id) => {
e.preventDefault()
let product_list = []
let productCost = document.getElementById('projectcost').value;
let productQty = document.getElementById('productQty'+id).value;
let productId = id;
if(localStorage.getItem('myItems')){
product_list = JSON.parse(localStorage.getItem('myItems'))
product_list.push({productId,productCost,productQty})
localStorage.setItem('myItems',JSON.stringify(product_list))
}else{
product_list.push({productId,productCost,productQty})
localStorage.setItem('myItems',JSON.stringify([{productId,productCost,productQty}]))
}
}
Output
[{"productId":43,"productCost":"320","productQty":"2"},{"productId":43,"productCost":"480","productQty":"3"},{"productId":44,"productCost":"420","productQty":"3"}]
When I want to insert same value I want the output to be
[{"productId":43,"productCost":"480","productQty":"3"},{"productId":44,"productCost":"420","productQty":"3"}]
To avoid that you push the same product a second time, first filter out the object that might concern the same product:
let productCost = +document.getElementById('projectcost').value;
let productQty = +document.getElementById('productQty'+id).value;
let product_list = JSON.parse(localStorage.getItem('myItems') ?? "[]");
.filter(({productId}) => productId != id)
.concat({productId: id, productCost, productQty});
localStorage.setItem('myItems', JSON.stringify(product_list));
Related
I am trying to save input values submitted through form into local storage in the form of the array, but once the form is submitted again, the saved value in local storage gets changed with the new submitted value as the
function bookDetails(bookName,bookAuthor,bookType) {
this.name = bookName;
this.author = bookAuthor;
this.type = bookType;
}
let libraryForm = document.getElementById("bookForm");
libraryForm.addEventListener("submit", libraryBooksDetails);
function libraryBooksDetails(e,index) {
e.preventDefault();
console.log("The book details have been submitted");
let bookName = document.getElementById("bookName").value;
let bookAuthor = document.getElementById("author").value;
let bookType;
let fiction = document.getElementById("Fiction");
let programming = document.getElementById("ComputerProgramming");
let personal = document.getElementById("PersonalDevelopement");
if(fiction.checked){
bookType = fiction.value;
}
else if(programming.checked){
bookType = programming.value;
}
else if(personal.checked){
bookType = personal.value;
}
// BookDetails Object
let book = new bookDetails(bookName,bookAuthor,bookType);
let bookData = ""
bookData = bookData || [];
let nameOfBooks = bookData.concat(bookName)
// let nameOfBooks = bookData
// nameOfBooks.push(book.bookName);
localStore.setItem("books",JSON.stringify(nameOfBooks))
console.log(book);
let display = new Display()
display.add(book);
display.clear();
}
Thanks
I'm not sure I understand the question completely because you are setting the value let book = new bookDetails but that is not what you are storing in local storage.
// First time bookData value is set, this is always an empty string
let bookData = "";
// Since empty string is a falsey value, bookData value is re-set to an empty array
bookData = bookData || [];
// nameOfBooks is initialised as an array with one value of bookName
let nameOfBooks = bookData.concat(bookName);
// books key in local storage is a stringified array with one item
localStore.setItem("books", JSON.stringify(nameOfBooks));
localStorage.setItem(key, value) will always replace the existing value at that key. If you want to append to the stored value, first get the value and parse it before appending the new value.
const oldValue = localStorage.getItem('books');
const parsed = JSON.parse(oldValue);
const newValue = parsed.concat(nameOfBooks);
localStorage.setItem('books', JSON.stringify(newValue));
i was working on a online shop . now everything is good but i want to do something to delete a product from my cart .here is its code can you help me?
function displaycart() {
let cartitems = localStorage.getItem("productsincart");
cartitems = JSON.parse(cartitems);
let productcontainer = document.querySelector(".products-container");
let cartcost = localStorage.getItem("totalcost");
if (cartitems && productcontainer ) {
Object.values(cartitems).map(item => {
productcontainer.innerHTML += '<tr><td><button class="bd">close</buttton></td><td>'+ item.nam + '</td><td>' + item.price * item.incart + '</td><td>' + item.incart + '<td>افزودن</td></tr>'
});
let productmab = document.querySelector(".mabb");
productmab.innerHTML += cartcost;
}
}
let bv = document.querySelector(".bv");
let bd = document.querySelectorAll(".bd")
let cc = localStorage.getItem("productsincart")
let cartiteme = JSON.parse(localStorage.getItem("productsincart"))
bv.addEventListener("click" , () => {
localStorage.clear()
window.alert("refresh the page")
})
displaycart()
and here is the localstorge ...
how can i delete one of them in productsincart ?
That could be an useful function in your case:
function removeItem(index) {
let cartitems = JSON.parse(localStorage.getItem("productsincart"));
cartitems.splice(index, 1);
localStorage.setItem('productsincart', JSON.stringify(cartitems));
}
One way is to give them ids. You could use npm i --save uuid to get random ids.
Your local storage should look like this:
[{"id": "342324", "product": "item"}, /* then repeated for every item */]
Then you remove the entry by creating a new array that doesn't contain the object with the specified id, then you replace the previous local storage array with the new one. You can filter like this:
const newLocalStorage = JSON.parse(localStorage.getItem("productsincart").filter((product) => product.id !== id);.
Then set local storage to newLocalStorage.
cartitems is an array and the entire array is stored in local storage. You just need to remove the desired item from the array and then write it back to local storage, which will overwrite the previous value.
I am practicing blog stuff. posting and deleting posts. mini social media I can say. And I wanted to save posts on localStorge. however I could save only 1 post at a time. and then I wanted to do it with IDs.
I create id with random number generator:
let newId = Math.floor(Math.random() * (1000000 - 100000) + 100000)
let postContents = {
ID : newId,
text: value,
}
an then I upload those values in let storedPosts = [] array.
then I save it to local storage with JSON:
let toJson = () => {
localStorage.setItem('storedPosts', JSON.stringify(storedPosts));
}
and then I get it from Local Storage:
let storedJsonPosts = localStorage.getItem('storedPosts')
let storedPosts_toUpload = JSON.parse(storedJsonPosts)
and then I join these two arrays together:
let storedPostsArray = storedPosts.concat(storedPosts_toUpload)
and after this I don't know what to do. I tried this:
let uploadStoredPosts = () => {
for (let i = 0; i < storedPostsArray.length; i++) {
let post = document.createElement('div')
$post_place.appendChild(post)
let text = document.createElement('p')
post.appendChild(text)
text.textContent = storedPostsArray[i].text
}
}
but it showed this:
It couldn't reach array values. plz help
Is this something that you're after?
The code reads from localStorage, parses that information, returns an empty array if it's the first time the user posted, pushes a new value to the array, stores that array by stringifying it, and the appending the new value to the document.
If you want the page to read from localStorage on page load, you need to add a function that reads from localStorage, and then loops through all posts to add each one of them by using appendToDocument().
StackOverflow doesn't allow the use of localStorage, so I used a variable for demo purposes.
I left out id as a property. You can play around with that by yourself, but I would suggest to use a timestamp as a foreign key ("id").
var justForDemoPurpose = null;
const addPostBtn = document.getElementById("add-button");
const addPostInput = document.getElementById("add-post");
const postContainerEl = document.getElementById("post-container");
addPostBtn.addEventListener('click', addPost);
function readFromLocalStorage(key) {
let localStorageItem = JSON.parse(justForDemoPurpose);
// let localStorageItem = JSON.parse(localStorage.getItem(key));
console.log('returning items:', localStorageItem);
return localStorageItem;
}
function storeInLocalStorage(key, value) {
justForDemoPurpose = JSON.stringify(value);
// JSON.stringify(localStorage.setItem(key, value));
}
function addPost() {
let postValue = addPostInput.value;
if (postValue) {
const LOCAL_STORAGE_KEY = 'posts';
let storedPosts = readFromLocalStorage(LOCAL_STORAGE_KEY) || [];
storedPosts.push(postValue);
storeInLocalStorage(LOCAL_STORAGE_KEY, storedPosts);
appendToDocument(postValue);
}
}
function appendToDocument(postValue) {
let divEl = document.createElement('div')
divEl.textContent = postValue;
postContainerEl.appendChild(divEl);
}
<div class="addPostContainer">
<input id="add-post" placeholder="Type here"> <button id="add-button">Add Post</button>
</div>
<section id="post-container"></section>
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 add an array localstorage. works fine. I can also retrieve it . how can I.update where ID is something without adding a new array.
example ..
how can I go update surname and age where ID = sam without creating new array
var objItem = {};
if (localstorage.getItem("records") == null) {
objArr = [];
} else {
objArr = JSON.parse(localstorage.getItem("records"));
}
var ID = "sam";
var surname = "edward";
var age = "two";
objItem.ID = ID;
objItem.surname = surname;
objItem.age = age;
objArr.push(objItem);
localstorage.setItem("records", JSON.stringify(objArr));
localStorage is just a key-value store. To update, you just save to the same key. That is, you retrieve your array, parse, update, stringify then save to the same key.
To find the item on the array, you can use array.filter and create an array containing only the values that match the ID. Update the values inside that array and save the original array.
let names = [...names...];
let matches = names.filter(person => person.ID === ID);
matches.forEach(person => person.surname = surname);
let toSave = JSON.stringify(names);
// save to localstorage