How to save Items in Local Storage with specific ID - javascript

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>

Related

Trying to push items in an array to store in localstorage

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')) || [];

Push all objects after a selected object into an array

I have a web page that returns a list of objects like:
date.pdf
names.csv
address.pdf
age.csv
cost.csv
budget.csv
data.pdf
race.pdf
contractors.csv
When a user checks budget.csv, I want every object with the .csv extension from that point to be pushed into csv_files[]. If they select names.csv, then every .csv including and after names is pushed into the array.
So the only data that gets pushed into the array is from the selected object downwards. How can I implement this?
Current code
const csv_files = []
$scope.listAllobjects = (err, data) => {
$.each(data.Contents, (index, value) => {
if (value.Key.endsWith("csv")) {
csv_files = [];
}
// Handle click on selection checkbox
$("#filesobjects-table tbody").on("click", 'input[type="checkbox"]', (e1) => {
const checkbox = e1.currentTarget;
const $row = $(checkbox).closest("tr");
const data = $tb.DataTable().row($row).data();
let index = -1;
// Prevent click event from propagating to parent
e1.stopPropagation();
// Find matching key in currently checked rows
index = $scope.view.keys_selected.findIndex((e2) => e2.Key === data.Key);
if (checkbox.checked && data.Key.endsWith("csv")) {
console.log(selected csv)
}
});
}
There's a few ways, I suppose, to approach this problem, but the most intuitive to me is this:
const csvList = ["date.pdf","names.csv","address.pdf","age.csv","cost.csv","budget.csv","data.pdf","race.pdf","contractors.csv"];
const selectedCsv = 'budget.csv';
function getCsvsAfter(csvList, selectedCsv) {
const filteredCsvs = [];
let found = false;
for (let csv of csvList) {
if (csv === selectedCsv) found = true;
if (found) filteredCsvs.push(csv);
}
return filteredCsvs;
}
console.log(getCsvsAfter(csvList, selectedCsv));
Iterate over every csv, and when you've hit the one you're trying to match, set a variable called found to true. Once it's true, you can add every following csv onto the list.
const list = ['date.pdf','names.csv','address.pdf','age.csv','cost.csv','budget.csv','data.pdf','race.pdf','contractors.csv'];
const selected = 'budget.csv'
const csv_files = list.slice(list.indexOf(selected))
console.log(csv_files)
Here you go with a pure JavaScript solution (Descriptive comments has been added in the below code snippet).
var contentData = ["date.pdf", "names.csv", "address.pdf", "age.csv", "cost.csv", "budget.csv", "data.pdf", "race.pdf", "contractors.csv"];
var myDiv = document.getElementById("cboxes");
for (var i = 0; i < contentData.length; i++) {
var checkBox = document.createElement("input");
var label = document.createElement("label");
checkBox.type = "checkbox";
checkBox.value = contentData[i];
myDiv.appendChild(checkBox);
myDiv.appendChild(label);
label.appendChild(document.createTextNode(contentData[i]));
}
// Event to handle the checkbox click
document.getElementById('getResult').addEventListener('click', () => {
document.getElementById('showResult').innerHTML = getCheckedValues();
});
function getCheckedValues() {
// filtered out the checked items.
const element = Array.from(document.querySelectorAll('input[type="checkbox"]'))
.filter((checkbox) => checkbox.checked).map((checkbox) => checkbox.value);
// element[0] will always return the first checked element and then we are getting index of that.
const checkedElemIndex = contentData.indexOf(element[0]);
// Slice the content data to get the elements from the checked element index.
return contentData.slice(checkedElemIndex, contentData.length)
}
<div id="cboxes"></div>
<button id="getResult">Get Result</button>
<pre id="showResult"></pre>

how to add an object to a list in localstorage

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);
}
}

history push is pushing two times same key

English is not my language so there might be mistakes, i'm beginner programmer(react hooks), my form(antd) data is moving in url, everything is working fine except going back and changing form input value to another then going again forward, i can see there is now two times same key but different value, my point is now there is for example 'name=james' and 'name=susan', but i want to have just one 'name' and it should be the latest, should i be pushing differently? below is also a picture i made about this, if it helps to understand. when console.log(query); it shows both 'names'
Next page function comes from here :
< Form onFinish={nextPage}>
< / Form>
i'm going back from page b to page a like this:
const query = window.location.toString().split("?")[1];
const handleclick = () => {
history.push(`/pagea/${custId}?${query}`);
};
history push in nextPage function is like this
const query = window.location.toString().split("?")[1];
const nextPage = (order: rRequest) => {
history.push(`/customers/${custId}?${query}&name=${order.name}`);
};
const query = window.location.toString().split("?")[1];
var qry = "";
if (query) {
qry = query.split("&");
for (var i = 0; i < qry.length; i++) {
var curr = qry[i].split("=");
if (curr[0] == "name") {
qry.splice(i, 1);
i--;
}
}
qry = qry.join("&");
}
const nextPage = (order: rRequest) => {
history.push(`/customers/${custId}?${qry}&name=${order.name}`);
};

How can I reformat API results into a dictionary then use that dictionary?

I have an assignment where I need to key an API using a key that cannot be used by default. Currently, I'm using getJSON to pull data from an API as seen in the code below:
$(document).ready(function() {
$.getJSON("https://api.nasa.gov/mars-photos/api/v1/manifests/curiosity?api_key=DEMO_KEY", function(data){
console.log(data);
});
});
This makes sense, but I'm stuck from here. Essentially, I'd like to reformat the API results and store them in a dictionary so I can key the results using "sol". Ideally, the dictionary would only contain the key "sol", its value, and the key "cameras", and its values for every section within photos as seen in the API.
Additionally, how would you then go about keying the dictionary using a sol value, and returning the cameras associated with that sol value?
EDIT:
The code below works great, but I'm not seeing what I would need to put after everything to use camera globally.
let new_dict = { "sol": {}, "cameras": {} };
$(document).ready(function(){
$.getJSON("https://api.nasa.gov/mars-photos/api/v1/manifests/curiosity?api_key=0L4UJKm4YYvddR1QdZdCihRwQIqKBGrPErgFqUsw", function(data){
let photos = data["photo_manifest"]["photos"];
let sol_arr = [];
for(x in photos){
let photo = photos[x];
let sol = photo.sol;
let cameras = photo.cameras;
sol_arr.push(sol);
new_dict["cameras"][sol] = cameras;
}
new_dict["sol"] = sol_arr;
let sol_value = 1;
let camera = new_dict["cameras"][sol_value];
});
});
$.getJSON("https://api.nasa.gov/mars-photos/api/v1/manifests/curiosity?api_key=DEMO_KEY", function(data){
let photos = data["photo_manifest"]["photos"];
let new_dict = { "sol" : {}, "cameras": {} };
let sol_arr = [];
for(x in photos){
let photo = photos[x];
let sol = photo.sol;
let cameras = photo.cameras;
sol_arr.push(sol);
new_dict["cameras"][sol] = cameras;
}
new_dict["sol"] = sol_arr;
});
for keying the dictionary using a sol value, you just need to put sol value
like
let sol_value = 1;
console.log(new_dict["cameras"][sol_value]); //this contains the cameras with the sol value 1

Categories