Home > other >  issues with localStorage and saving values
issues with localStorage and saving values

Time:09-25

I have a program where I have these strings being added to an array. However, there are many strings that are triggered by a certain condition, which can be met multiple times, however I only want it to be added on the first occurrence. So I have implemented a system where the event of adding the string to the array is triggered by the original condition, and a boolean expression. Here is an example of one of those conditions:

if (count >= 10 && displayMulti == true) {
        consoleData.shift()
        consoleData.push("Multi available")
        displayMulti = false
        window.localStorage.setItem("display_multi", String(displayMulti))
        updateConsole()
    }

When the string is added to the array, the boolean, displayMulti, is set to false so that it will not trigger again. However, upon refreshing the page, it will still trigger. I'm not sure why because I feel like I have saving the values to localstorage correctly. Code is below:

if (window.localStorage.getItem("display_multi") != null ) {
    displayMulti = Boolean(window.localStorage.getItem("display_multi"))
} else {
    console.log("here")
    var displayMulti = true
}

There "here" console log statement is not triggered. So I have no idea why this would keep triggering because I don't see how the boolean is true. I've tested at like so many different points I genuinely have no idea what's wrong. I also don't think those values are affected anywhere else in my code. Any help is appreciated.

CodePudding user response:

Here is a solution that properly parses your string as a boolean. Instead of Boolean(), a conditional (window.localStorage.getItem("display_multi") === 'true')(window.localStorage.getItem("display_multi") === 'true') is used.

if (window.localStorage.getItem("display_multi") != null ) {
    displayMulti = (window.localStorage.getItem("display_multi") === 'true')
} else {
    console.log("here")
    var displayMulti = true
}

if (count >= 10 && displayMulti == true) {
    consoleData.shift()
    consoleData.push("Multi available")
    displayMulti = false
    window.localStorage.setItem("display_multi", String(displayMulti))
    updateConsole()
}
  • Related