Store time in local storage - javascript

I'm trying to push a lapsed time to local storage. Whenever the user clicks a submit button a clock stops and a duration is calculated. I want to push that duration time to an array in local storage. And after the last click I want to fetch the entire array to calculate the total time. There are several similar questions in SO but none of them siuts this purpose fully. I can see in my local storage that an array with key: 'Time' has been created but it isn't populating.
Code:
let answerButton = document.querySelector('#send')
answerButton.addEventListener('click', function () {
TotalTime.stop()
TotalTime.duration()
clearTimeout(window.countdownTimer)
timer()
let totalTime = []
TotalTime.duration().push(window.localStorage.setItem('Time', JSON.stringify(totalTime)))
})

Related

Local Storage gets refreshed when I refresh the page

I am building a notes app. I want to save the notes entered by the user in the Local Storage so that I can get it even after I refresh my page. The local storage is working properly but as soon as I refresh the items from the local storage get deleted.
const [notes, setNotes] = useState([]);
// This is the state variable that contains all the notes that are entered by the user.
useEffect(() => {
window.localStorage.setItem('react-notes-app-data', JSON.stringify(notes));
}, [notes]);
useEffect(() => {
const data = window.localStorage.getItem('react-notes-app-data');
if (data !== null) setNotes(JSON.parse(data));
}, []);
I have used these two useEffect() hooks. The first one adds the note entered by the user into the local storage, every time the notes state gets updated. I have given it a key of 'reacet-notes-app-data'.
The second useEffect() is supposed to render the notes from the local storage, the first time I render my page. So I check if the data is null or not. If it is not null I update the notes array with the elements already present in the local storage. But it does not show the already present items. Basically when I refresh the local storage gets refreshed too and gets empty.
When the page gets refreshed the initial state of notes set as an empty array []
Solution:
const savedNotes = JSON.parse(localStorage.getItem('react-notes-app-data'));
const [notes, setNotes] = useState(savedNotes || []);
Hope it works fine. If it still does not work then please share the code where you update the state notes.

How to remove local storage value only on initial loads of the component

I have a situation where I have some values in stored local storage. I want to clear those values when the page loads for the first time. But, after that, if I want to set those values again,I should be able to do this and page refresh shouldn't remove this as well. So. the question is: are there any ways of doing something only on initial loads of the component and don't do anything afterwards.
Yes, that is the typical use of sessionStorage. It works the same way as localStroage, but it will be clear after users closes browsers. However, between page reloads, it is preserved.
You can use it like this:
// Save data to sessionStorage
sessionStorage.setItem('key', 'value');
// Get saved data from sessionStorage
const data = sessionStorage.getItem('key');
You can create a count variable and when react app runs for the first time useEffect will remove required items from localstorage and will set count to 1 in localstorage and then everytime component re-renders it will check in localstorage if count is 1 if it is 1 then it won't remove item from localstorage.
useEffect(() => {
if(localStorage.getItem('count') !== '1') {
localStorage.removeItem('val')
localStorage.setItem('count', '1')
}
set()
}, [])
const set = () => {
localStorage.setItem('val', 'skndkj')
}

localstorage not updated after refresh angular

After I refresh my browser to retrieve data from localstorage and update that data, it's not updated. But when I add new items and update it, it is updating. What's seems to be the problem here?
//----- update existing item's subtotal in localstorage
changeSubtotalOfExisting(qty ) {
let updateQty = JSON.parse(localStorage.getItem('cart_items'));
updateQty['qtyTotal'] = qty;
localStorage.setItem("cart_items", JSON.stringify(updateQty));
console.log('updateQty: ', updateQty );
}
Here's a stackblitz sample:
https://stackblitz.com/edit/angular-ivy-i8kpub?file=src/app/app.component.ts
There were several problems with your implementation. Failing to save to local storage was only one of them. I ended up rewriting a lot of it, and actually simplifying considerably. I apologize if this was not your intention in your question. Here is the resulting project: https://stackblitz.com/edit/angular-cart-local-storage. You can compare the 2 projects.
I'm listing here some key issues:
Accessing local storage should be done only from the service, not from the component. The service is in charge of saving and retrieving data. The component is in charge of interacting with the user.
You saved to local storage the wrong objects (and maybe this is the answer to your original question). Local storage should store the cart (a list of items). Here for example you're trying to save to local storage as if it stores only one item at a time:
updateQty['qtyTotal'] = qty;
localStorage.setItem("cart_items", JSON.stringify(updateQty));
Your event handlers are called with the wrong arguments. You need to call them with the item as an argument, not the HTML element. Instead of changeSubtotal($event.target, addedItem.variationCost,i) I call changeSubtotal(item ,i)
You did not prevent the user from adding the same item to the cart multiple times.
The initial quantity of an item you add to the cart should be 1 and not 0, as you set the minimum of the quantity control to 1

[PHP][MySQL] Erased table after 60 seconds of recording

Im working on kinda program which main part is to count the time which user spent on website, and then to save recorded time in database.
How it works: on the page user has button to start recording his time, then he gets moved to another page, where he can save his time. Saved time is being sent to the php file (through ajax), and then php file puts value in database for current user.
THE PROBLEM is that after 60 seconds of recording time - table in database starts from scratch (00:00:00). For example: if user has already recorded 30 seconds (00:00:30), then he runs the script, records 40 seconds more, and then instead of 00:01:10 in database his score is clear (00:00:00)
Details below.
MySQL Table - type: time
//JS
$("#stopTimer").click(function(event) {
var time = event.timeStamp;
$.ajax({
type: 'POST',
async: true,
url: 'timer.php',
data: {time: time}
});
});
//PHP
$time = ($_POST['time']/1000);
$stmt = $db->prepare("UPDATE members SET timeOnline = timeOnline + '$time' WHERE memberID = :memberID");
$stmt->execute(array(':memberID' => $memberID));
If you want to add seconds to a TIME column use + INTERVAL x SECOND:
UPDATE members
SET timeOnline = timeOnline + INTERVAL :time SECOND
WHERE memberID = :memberID
Try it in another way.
Keep one extra column named start_time . When user first press this button store current time on that.
When user browse in different pages, just calculate the time difference in timeOnline .
It will also be simpler.

variable value on page change

I am new in javascript and php. I am creatng an admin panel in which I have an option for the user to play game. But the issue is, every game have a specific time period say 30 mins. So, what I want is that if a user have started the game, the count down must be started and if user once switch from that page to another page, still the counter must be counting and after 30 mins it should end the game.
For example I am on http://www.examplec.com/Game1 my count down of 30 min will start. If I switch from that page to another like http://www.example.com/order then the counter should still count the total time and when its expired, end it and send query to database.
Kindly reply if anyone know the solution. I have already find a solution using session but I want more efficient solution. One more thing a single user can play more than 1 game.
when your game start set a session of current time like this
$_SESSION['game_start_time'] = strtotime(date('d-M-Y g:i:s A')); // it will give you complete current timestamp.
and now check it on every page by including
if(isset($_SESSION['game_start_time']))
{
$game_start_time = $_SESSION['game_start_time'];
$current_time = strtotime(date('d-M-Y g:i:s A'));
$time_diff = $current_time - $game_start_time;
if($time_diff>(30*60))
{
//expire 30 minutes your code is here
}
else
{
// action if require to do when below 30 minutes of game start.
}
}
What you could do is create a table to keep track of the time, this is not the most efficient way but it would be secure.
So create a new table called gametrack with the following fiels:
id
userid
gameid
timestarted
etc
so when a user starts a game you insert a record with user info.
Next you need to edit the game page. In the game page you could place a jquery code to request for update on the time.
function gameStatus(){
$.ajax({
url: 'status.php?gid=[GAMEID]',
success: function(data) {
if(data == 1) {
//DO SOMETHING, REFRESH THE PAGE, STOP THE GAME ETC
}
}
});
}
setInterval("gameStatus()",10000);
the code above would request status.php every 10 seconds, you need to pass the gameid to the file and assuming that the user is registered you can use session to get user info and return 1 if 30 mins has passed.
You can mix this solution with Satish's Answer to use Sessions instead of Databases and still get a live count down with the jquery code above.
You can try this with localStorage
When you want to set variable:
var name = "value";
localStorage.setItem("someVarName", name);
And in any page (like when the page has loaded), get it like:
var Name = localStorage.getItem("someVarName");
Browser compatibility caniuse.com/namevalue-storage
Demo

Categories

Resources