How to save localstorage - javascript

How to save user data in localstorage even after refreshing
localStorage.setItem('bas',JSON.stringify(basketList));
const objectorage = JSON.parse(localStorage.getItem('object'));
Which command is more correct for storage?

This command localStorage.setItem('bas',JSON.stringify(basketList)); use to save data to localStorage with key is bas.
And this command localStorage.getItem('bas') is get data from localStorage with key is bas.
localStorage storage string data. So you get data from localStorage, you need parse it to object using JSON.parse(localStorage.getItem('bas'));.
Hope this help!

Your code seems ok.
To save a new object in localstorage use:
localStorage.setItem('userData', JSON.stringify(userData));
To get an existing object in localstorage use:
const myuserdata = JSON.parse(localStorage.getItem('userData'));
For more info check
setItem
getItem

Which command is more correct for storage?
None of them is "more correct" than the other. They are two different commands with different purposes:
localStorage.setItem(keyName, keyValue) stores data in the local storage under the provided keyName.
localStorage.getItem(keyName) retrieves the value stored under the provided keyName.
So, in your code:
localStorage.setItem('bas',JSON.stringify(basketList));
const objectorage = JSON.parse(localStorage.getItem('object'));
The first command stores the stringified basketList under the key bas. The second command tries to get the value stored under the key object, which doesn't exist in this case. The second command should instead be:
const objectorage = JSON.parse(localStorage.getItem('bas'));

According to Geeksforgeeks, localStorage has no expiration time.
You can test it with these steps:
Set an Item
basketList = ['a','b']; localStorage.setItem('bas',JSON.stringify(basketList));
Refresh it and print the value
JSON.parse(localStorage.getItem('bas'));
https://www.geeksforgeeks.org/localstorage-and-sessionstorage-web-storage-apis/#:~:text=LocalStorage%20has%20no%20expiration%20time,the%20user%20manually%20delete%20it.

Related

Getting specific values of key from Local Storage [JS][HTML5][React][LocalStorage]

I have a problem to get the specific value of my key.
I created the array "UserLoggingData" (key) with the values of 'password','email' and 'id' (Time Stamp)
that are stored in the object User and saved in the local storage.
The parameters email and password are taken from a form.
let login_data =[];
const addUser = (ev)=>{
ev.preventDefault();
let user = {
id : Date.now(),
email:document.getElementById('email').value,
password:document.getElementById('password').value
}
login_data.push(user);
document.forms[0].reset();
console.log(login_data);
//save to local storage
localStorage.setItem('UsersLoggingData',JSON.stringify(login_data));
Then I get such result in Local Storage:
How do I get to the specific password or email? How can I display them or get them so I can operate on them afterwards?
I tried localStorage.getItem('UserLoggingData')
but it shows null.
I need this for my diploma thesis so thanks for help in advance!
You have to parse the string you will get from localStorage.getItem(). Once you've done this you will have an array (based on your screenshot). This code should log the first email in your console :
const data = JSON.parse(localStorage.getItem(UsersLoggingData));
console.log(data[0].email)

Save data from GET request as variable

I've got a simple axios GET request that is working with Azure directline 3.0. The GET request pulls back data and shows it in the console (as seen in the picture).
The data I want to save into a variable is the conversationId. I then want to use this variable with Axios Post in another JS file to post as part of the link e.g. let URL = "https://directline.botframework.com/v3/directline/conversations/"+convID"/activities". With convID being the variable I wish to create. Right now I am manually changing the convID with the new conversation ID, but I want to create a variable so I can place it in the post javascript file so it is automatic.enter image description here
There are various ways you can solve this problem. Easiest one being, exposing the data on a shared object window.convID = convID and then accessing it wherever required.
You could also look to make singleton objects, which can be instantiated only once and hence will share it's variables across the lifespan of the application.
axios.get(/* URL */).then(res => {
window.convID = res.data.conversationId;
});
You can save that variable value in LocalStorage. Something like this:
let routeToYourApi = '/api/conversations'; // or something like this...
axios.get(routeToYourApi).then((response) => {
let conversationId = response.data.conversationId; // not sure if data object from your image is directly nested inside response that you get from server, but you get the idea...
window.localStorage.setItem("convId", conversationId);
}) // here you can fetch your conversation id
Than you can access it anywhere in your app:
let conversationId = window.localStorage.getItem("convId");
... and eventually remove it from local storage:
window.localStorage.removeItem("convId")
Hope this will help you!

Linking to elements within different documents

I have used the 'prompt' method into asking for a character name. however i am wandering if i can save that data to then use again in different html documents, to use the characters name in context. I am currently using Javascript and would like to try and use that to solve this issue.
You can use localStorage to access the data input by user on another page (must be same origin).
var value = prompt('Please enter your name');
if (value) {
localStorage.setItem('username', value);
}
To get the saved data on another page, use:
localStorage.getItem('username');
Just assign a variable prompt function. The user input will be saved in this variable.
var saveMe = prompt('What time is it?')
console.log (saveMe)
If you want to store data and use them only locally you should maybe use the local storage, this allow you to save data into the user's browser. But you should know that old browsers do not support that.
Look at the W3School class about local storage.
Here is an example of how it works :
localStorage.setItem("userName", prompt('Your name'));
And then when you need to access it :
localStorage.getItem("lastname");

Saving Usernames in Local Storage. Only by using one key.

I want to save and get out the Usernames from the Local Storage. I can only save and get out one Username with one key. Is it possible to save the Usernames in an array so that I can list them later ? I think it actually overwrites itself..
//Saving the username from input field to the Local Storage
top.username=document.getElementById("name").value;
localStorage.setItem('user', top.username);
//Getting out the username from the Local Storage
document.getElementById('list').innerHTML =localStorage.getItem('user');
Thanks for your help!
You can do something like this:
localStorage.setItem('arrayOfUserNames', JSON.stringify(['foo']))
var arrayOfUserNames = JSON.parse(localStorage.getItem('arrayOfUserNames'))
arrayOfUserNames.push('bar')
localStorage.setItem('arrayOfUserNames', JSON.stringify(arrayOfUserNames))
arrayOfUserNames = JSON.parse(localStorage.getItem('arrayOfUserNames'))
console.log(arrayOfUserNames) // ["foo", "bar"]
You can do something like this:
let loginForm = this.loginForm.value;
localStorage.setItem('userName', JSON.stringify([loginForm.userName]));
localStorage.setItem('password', JSON.stringify([loginForm.password]));

how to localhost saved values check using javascript

how to localhost saved values check using java script,Button on click based saving one value,after page refresh want to check check value save,How to check
Dear you can use SESSION variable for it. You can store checked checkbox value in an index on array and that array stored in Session Variable. So by this way you will get all checked values and can use anywhere.
What is HTML5 Web Storage?
With HTML5, web pages can store data locally within the user's browser.
Earlier, this was done with cookies. However, Web Storage is more secure and faster. The data is not included with every server request, but used ONLY when asked for. It is also possible to store large amounts of data, without affecting the website's performance.
The data is stored in name/value pairs, and a web page can only access data stored by itself.
Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server.
Example:
function getItem(key){
if (!hasLocalStorage || !key) return;
return localStorage.getItem(key);
}
function setItem(key, val){
if (!hasLocalStorage || !key) return;
localStorage.setItem(key, val);
}
function hasLocalStorage () {
return typeof window.localStorage !== 'undefined';
}
//to store an item
setItem("itemKey", "itemVal");
//to retrieve an (the above, in this case) item
var fetchItem = getItem("itemKey");
Did you try to store that value in cookies?

Categories