How to use javascript localstorage to add pokemon to favorites

I am pretty new with localstorage
, JS in general, but my question is how can i favorite my pokemon by using localstorage. Basically a toggle function if it’s already registerd as added to favorites, it’ll unfavorite if you’ll press on the button again. I have the code i need, but it doesn’t favorite the pokemon.

So here’s the thing i tried. First of all i managed to get fix it (with the help of ChatGPT). But the problem is that i can’t use it’s code, because i haven’t learnt that specific code ChatGPT gave me, and i want to do this on my own. THis is their code:

window.addEventListener('load', init);
let name;
let tags;
let favorite;

function init() {
    if (typeof window.localStorage === "undefined") {
        console.error('Local storage is not available in your browser');
        return;
    }
}
document.addEventListener('DOMContentLoaded', function () {
    const containers = document.querySelectorAll('.container');

    // Check localStorage for favorites data
    const favorites = JSON.parse(localStorage.getItem('favorites')) || {};

    // Function to update favorite status
    function updateFavoriteStatus(id) {
        if (favorites[id]) {
            containers[id - 1].classList.add('favorite');
        } else {
            containers[id - 1].classList.remove('favorite');
        }
    }

    //  click event to each "Add to Favorites" button
    document.querySelectorAll('.add-to-favorites').forEach((button, index) => {
        button.addEventListener('click', function () {
            const containerId = index + 1;

            // Toggle favorite status
            favorites[containerId] = !favorites[containerId];

            // Save to localStorage
            localStorage.setItem('favorites', JSON.stringify(favorites));

            // Update favorite status
            updateFavoriteStatus(containerId);
        });

        // Initial update of favorite status
        updateFavoriteStatus(index + 1);
    });
});

So, this works. I reworked the code on my own, but here lies the problem. So whenever i tried running it, i couldn’t see all of my containers. Second of all when i checked for any errors i got this: TypeError: favorite is not iterable
at getPokemonSuccesHandler (task.js:87:30). So i scoured the internet and the problem was that it expected an array. So i found out i could use if (!Array.isArray(favorite)) { favorite = []; }
. I saw my containers, but the button still didn’t work. How can i fix the problem? It’d also be cool when a pokemon has been favorited, the container of the pokemon would get a different color. Here’s my reworked code:

window.addEventListener('load', init)
let name;
let tags;
let favorite = JSON.parse(localStorage.getItem("favorites")) || [];
let apiurl = 'http://localhost/prg03-eindopdracht/webservice/index.php';
let gallery;
let pokedata = {};
function init() {
let gallery = document.getElementById('gallery');
gallery.addEventListener('click', pokemonClickHandler)
    ajaxRequest(apiurl, getPokemonSuccesHandler)
    let title = document.getElementById('title');
gallery.appendChild(title);

}

// document.addEventListener('DOMContentLoaded', function () {
//     const containers = document.querySelectorAll('.container');
//
//     // Check localStorage for favorites data
//     const favorites = JSON.parse(localStorage.getItem('favorites')) || {};
//
//     // Function to update favorite status
//     function updateFavoriteStatus(id) {
//         if (favorites[id]) {
//             containers[id - 1].classList.add('favorite');
//         } else {
//             containers[id - 1].classList.remove('favorite');
//         }
//     }
//
//     //  click event to each "Add to Favorites" button
//     document.querySelectorAll('.add-to-favorites').forEach((button, index) => {
//         button.addEventListener('click', function () {
//             const containerId = index + 1;
//
//             // Toggle favorite status
//             favorites[containerId] = !favorites[containerId];
//
//             // Save to localStorage
//             localStorage.setItem('favorites', JSON.stringify(favorites));
//
//             // Update favorite status
//             updateFavoriteStatus(containerId);
//         });
//
//         // Initial update of favorite status
//         updateFavoriteStatus(index + 1);
//     });
// });
function ajaxRequest(url, successCallback) {
    fetch(url)
        .then((response) => {
            if (!response.ok) {
                throw new Error(response.statusText);
            }
            return response.json();
        })
        .then(successCallback)
        .catch(ajaxRequestErrorHandler);
}


/**
 *
 * @param data
 */
function getPokemonSuccesHandler (data) {
    console.log('a')
    let gallery = document.getElementById('gallery');
    if (!Array.isArray(favorite)) {
        favorite = [];
    }

    for (let mons of data) {
        let pokemonContainer = document.createElement('div');
        pokemonContainer.classList.add('container');

        let title = document.createElement('div');
        title.classList.add('food-name');
        title.innerHTML = `${mons.name} (#${mons.id})`;
        pokemonContainer.appendChild(title);
        let buttonContainer = document.createElement('div');
        buttonContainer.classList.add('button-container');

        let addToFavoritesButton = document.createElement('button');
        addToFavoritesButton.classList.add('button', 'add-to-favorites');
        addToFavoritesButton.innerHTML = 'Add to Favorites';
        addToFavoritesButton.dataset.id = mons.id;
        // replace class add-to-favirte with added
        for (let checkFav of favorite) {
            if (checkFav === mons.id) {
                addToFavoritesButton.classList.replace("favorites", "added")

            }

        }
        buttonContainer.appendChild(addToFavoritesButton);

        let showInfoButton = document.createElement('button');
        showInfoButton.classList.add('button', 'show-info');
        showInfoButton.innerHTML = 'Show Info';
        buttonContainer.appendChild(showInfoButton);

        pokemonContainer.appendChild(buttonContainer);
        let image = document.createElement('img');
        image.src = mons.img;
        console.log(image)
        pokemonContainer.appendChild(image)

        // append containers to the gallery
        gallery.appendChild(pokemonContainer);
        pokedata[mons.id] = mons;
    }


}

/**
 *
 * @param e
 */
function pokemonClickHandler (e) {
    let clickedItem = e.target;
    let globmons = pokedata[clickedItem.dataset.id];

    if (clickedItem.nodeName !== `BUTTON`) {
        return;
    }
    if (clickedItem.classList.contains('favorites')){
        addFavorites(clickedItem)
        console.log("Toegevoegd als fav!")

    }
    else if (clickedItem.classList.contains('added')){
        removeFavorites(clickedItem)
        console.log("ah")
    }

}
function addFavorites(game){
    game.classList.replace("favorites", "added")
    favorite.push(game.dataset.id);
    localStorage.setItem("favorites", JSON.stringify(favorite));

}
function removeFavorites(game){
    game.classList.replace("added", "favorites");
    let index = favorite.indexOf(game.dataset.id);
    favorite.splice(index, 1);
    localStorage.setItem("favorites", JSON.stringify(favorite));

}
function ajaxRequestErrorHandler (data) {
    console.log(data)
}
// window.addEventListener('load', fetchData);