skip to Main Content
export default function Track({ data, setPlaylist, playlist }) {
  function handleAdd(song) {
    console.log(song.id);

    if (!playlist === song) {
      setPlaylist((playlist) => [...playlist, song]);
    }
  }

  return (
    <div className="tracks">
      {data.map((song) => (
        <div className="box" key={song.id}>
          <h2>{song.name}</h2>
          <h3>by {song.artist}</h3>
          <p> from {song.album}</p>
          <button onClick={() => handleAdd(song)}> + </button>
        </div>
      ))}
    </div>
  );
}

Building a playlist site for class project with Spotify api. It adds and removes items from the playlist (removal function isn’t in this file), but when I add the logic to the function it stops adding the new items to the array at all. Apreciated.

2

Answers


  1. playlist is array, you need to check if it contains song. You may do it by find function.

    For example, instead of if (!playlist === song) do:

    if(playlist.find(s => s.name === song.name && s.artist === song.artist))
    
    Login or Signup to reply.
  2. In your handleAdd function, the logic for checking whether a song is already in the playlist seems incorrect. When comparing arrays or objects, direct comparison like playlist === song compares their references, not their contents.

    Instead, you should check if the song’s ID is already present in the playlist array.

    Here’s the corrected function:

    function handleAdd(song) {
        console.log(song.id);
    
        // Check if the song is already in the playlist
        if (!playlist?.some(item => item.id === song.id)) {
            // If the song is not in the playlist, add it
            setPlaylist([...playlist, song]);
        }
    }
    

    Happy Coding

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search