Skip to content
Advertisement

Toggle button JS changing value in LocalStorage

I am trying to create a favourite button next to a list which a person can toggle on and off whenever he wants and store a value inside the localstorage so it will be saved on refresh. How would I create a button which when clicked it will turn yellow and update the localstorage to “favourite”: True, and if pressed again the button will turn back to default and update local storage to “favourite”: False. Thanks

function favourite(element) {

    var allPlaces = JSON.parse(localStorage.getItem("allPlaces"));

    if (allPlaces.favourite == true) {
        allPlaces.favourite = false;
        element.querySelector('ion-icon').setAttribute('name', 'star-outline');
    } else {
        allPlaces.favourite = true;
        element.style.color = '#FFE234';
        element.querySelector('ion-icon').setAttribute('name', 'star');
    }
    localStorage.setItem("allPlaces", JSON.stringify(allPlaces));
}

These are the objects inside the Local Storage (LS)

“title”: title,
“description”: description,
“category”: category,
“favourite”: false

Advertisement

Answer

You should conditionally render the button based on the favourite prop, so when favourite have to change you should set the new value in tha localStorage

First retrieve the object with JSON.parse

let place = JSON.parse(localStorage.getItem('myPlaces'))

and then change directly the “favourite” prop

let newValue = {
...place,
favourite: false}

and store the new object in the localStorage:

const newPlaceStringified = JSON.stringify(newValue)
localStorage.setItem('myPlaces', newPlaceStringified )

So the next time your favourite is saved correctly and can render conditionally the button and the logic

function favourite(element) {

    var allPlaces = JSON.parse(localStorage.getItem("allPlaces"));

    if (allPlaces["favourite"] == true) {
        
        localStorage.setItem(
                      'myItem',
                      JSON.stringify({
                        ...item1,
                        favourite: false,
                       }),
       )
    
        element.querySelector('ion-icon').setAttribute('name', 'star-outline');

    } else {
            localStorage.setItem(
              'myItem',
              JSON.stringify({
                ...item1,
              favourite: true,
               }),
            )

        element.style.color = '#FFE234';
        element.querySelector('ion-icon').setAttribute('name', 'star');
    }
    

    
}

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement