Search code examples
javascriptjqueryajaxapispotify

Save data from Ajax call about artist on page, but only once for a particular artist


I'm developing a simple one-page application using Spotify REST API and JQuery, that allows users to search for an artist and save the artist's information on-page. But the app should save info about a particular artist only once (for example, there shouldn't be 2x Beatles). The source code is below. Thanks!

addButton.click(() => {
    // .....
    $.ajax({
        url: `${baseUrl}search?q=${searchQuery}&type=artist`,
        type: 'GET',
        datatype: 'json',
        headers: {
            'Authorization': 'Bearer ' + accessToken
        }
    }).done((resp) => {

        const rawArtistName = (resp.artists.items[0].name);
        const imageUrl = (resp.artists.items[0].images[0].url);
        const followers = (resp.artists.items[0].followers.total);
        const artistId = (resp.artists.items[0].id);

        const artistWrapper = $(`<div class ="artist-stats"><div>`);
        const artistImage = $(`<img src="${`${imageUrl}`}" alt="queen" width="200", height="200">`);
        const artistName = $(`<p id="nameNumber">${rawArtistName}</p>`);
        const artistFollowers = $(`<p> followers: ${followers} </p>`);
        const deleteArtist = $(`<button id="delete-button"> go away </button>`);


        artistList.append(artistWrapper);
        artistWrapper.append(artistImage);
        artistWrapper.append(artistName);
        artistWrapper.append(artistFollowers);
        artistWrapper.append(deleteArtist);

        
        const existingArtistNames = $(' #nameNumber')
    
// this is my attempt ->
        for (let i = 0; i < existingArtistNames.length; i++) {
            const existingArtistName = existingArtistNames[i].text();
            if ( something === something) {
                alert('artist is already here');
                return false;
            }
        }

Solution

  • Do not use any id in that .done because it will create multiple times the same id... And an id must be unique. Use a class instead.

    With a class, you can iterate the elements previously created. See below:

    }).done((resp) => {
    
        const rawArtistName = (resp.artists.items[0].name);
        const imageUrl = (resp.artists.items[0].images[0].url);
        const followers = (resp.artists.items[0].followers.total);
        const artistId = (resp.artists.items[0].id);
    
        const artistWrapper = $(`<div class ="artist-stats"><div>`);
        const artistImage = $(`<img src="${`${imageUrl}`}" alt="queen" width="200", height="200">`);
        const artistName = $(`<p class="nameNumber">${rawArtistName}</p>`);
        const artistFollowers = $(`<p> followers: ${followers} </p>`);
        const deleteArtist = $(`<button class="delete-button"> go away </button>`);
    
        // Assuming it's not...
        let alreadyOnPage = false;
        // Check all the artist names
        $(".nameNumber").each(function(index,element){
          if($(element).text() === rawArtistName){
            // It found it!
            alreadyOnPage = true;
          }
        })
    
        // append the element only if not already on page
        if(!alreadyOnPage){
    
          artistList.append(artistWrapper);
          artistWrapper.append(artistImage);
          artistWrapper.append(artistName);
          artistWrapper.append(artistFollowers);
          artistWrapper.append(deleteArtist);
        }
    
        else{
          alert('artist is already here');
        }
      })