'local storage in browser not incrementing?
I'm trying to build a date booking feature that returns the total cost of a booking based on the dates selected and the cost associated with that booking.
I have converted the dates into milliseconds and I'm looping through the possible date ranges that costs are assigned to (15th dec - 15th jan = 220 dollars per night for example).
I then want to store in local storage the count of times that a date falls within a particular date range so I can just do the math at the end of multiplying the number of times dates fall within a date range and multiple by that cost.
My issue is i'm not sure if I am correctly incrementing the count in the local storage as shown in the screenshot below
for (let i = 0; i < daysDifference; i++) { //for loop to go through each day
let dayDot = startTime + (i * 86400000); // getting the range for each day of the booking in millisecs
localStorage.setItem("dayscost0", "0") //setting day count in each range to zero in local storage
if (dayDot <= 1639746000000 && dayDot >= 1634648400000) { // setting range for price blocks
let cost = (parseInt(localStorage.getItem('dayscost0')) + 1); //incrementing by one each time a value fits the range
localStorage.setItem("dayscost0", cost.toString()) //adding the value to local storage
console.log('dayscost0')
}
Solution 1:[1]
Problem is thers is always reinitialization - localStorage.setItem("dayscost0", "0")on each iteration. Try moving it outside of the for-loop.
localStorage.setItem("dayscost0", "0") //setting day count in each range to zero in local storage
for (let i = 0; i < daysDifference; i++) { //for loop to go through each day
let dayDot = startTime + (i * 86400000); // getting the range for each day of the booking in millisecs
if (dayDot <= 1639746000000 && dayDot >= 1634648400000) { // setting range for price blocks
let cost = (parseInt(localStorage.getItem('dayscost0')) + 1); //incrementing by one each time a value fits the range
localStorage.setItem("dayscost0", cost.toString()) //adding the value to local storage
console.log('dayscost0')
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
