Search code examples
javascriptspotifyspotify-app

setImage does not show the new image in JavaScript with Spotify Apps API


I am trying to set a different image with the setImage method.

The issue is that the new image becomes visible just for a very short period of time, but then fades away in to the original image.

Besides that, the play button disappears.

Here is my code:

require(['$api/models', '$views/image#Image'], function(models, Image) {

    // Play a single track
    var track = models.Track.fromURI('spotify:track:7B1Dl3tXqySkB8OPEwVvSu');
    var image = Image.forTrack(track, {player: true});

    // A line added by me to set the new image
    image.setImage("/img/spotify-logo.png");

    // Pass the player HTML code to the #single-track-player div
    document.getElementById('single-track-player')
        .appendChild(image.node);
});

This code is mostly taken from the Spotify Apps Tutorial.

The only line I have added is that with the setImage method.

What am I doing wrong?


Solution

  • There might be a race condition when setting the custom image using Image.setImage.

    A solution is to use the Image.fromSource method:

    require(['$api/models', '$views/image#Image'], function(models, Image) {
    
        // Play a single track
        var track = models.Track.fromURI('spotify:track:7B1Dl3tXqySkB8OPEwVvSu');
        var image = Image.fromSource("/img/spotify-logo.png", {
            playerItem: track,
            player: true
        });
    
        // Pass the player HTML code to the #single-track-player div
        document.getElementById('single-track-player')
            .appendChild(image.node);
    
    });