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
playlist
is array, you need to check if it contains song. You may do it byfind
function.For example, instead of
if (!playlist === song)
do: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 likeplaylist === 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:
Happy Coding