I’m on the second part of the Jammming project using React and the Spotify API. I’m trying to compare two strings, one held in the props within an array of objects and another held in the props within an object. I’m iterating over the array of objects then declaring the necessary string and comparing it to the string of this component. In the console on the values that do match, both evaluate to the same string (I’ve checked using typeof) but the comparison keeps evaluating to a falsy.
// function within a component class
isInPlaylist() {
if (this.props.playlistTracks) {
this.props.playlistTracks.forEach(playlistTrack => {
console.log(playlistTrack.uri) //reading "spotify:track:61mWefnWQOLf90gepjOCb3" as a string
console.log(this.props.track.uri) //reading "spotify:track:61mWefnWQOLf90gepjOCb3" as a string
if (playlistTrack.uri === this.props.track.uri) {
return true;
}
})
}
return false;
}
When both the console.logs are reading the same value this still returns as false. This applies to all matching values that are passed through the second if statement. Am I missing something?
Please help! I can’t tell if I’ve messed up in the logic of the code or if I’m genuinely missing something
are you sure that it actually returns false? Did youconsole.log(playlistTrack.uri === this.props.track.uri) to verify that or do you just miss an effect of your return statement?
That is because you use forEach. The forEach method does not return anything. What do you want to happen if true is returned?
I haven’t actually console logged playlist track uri, I’ll give that a try in a bit. Basically, if the function returns true (if a song is already in the playlist) I want the state of a button component to be ‘-’ rather than ‘+’.
I’ve just realised that the return statement within the loop probably returns true for the function within the forEach and not the function as a whole.
I’m pretty sure that it will log ‘true’. But that doesn’t have an effect within a forEach method. If you want the method to return anything, you’ll have to use .map() instead.
In your code I don’t see anything with this functionality.
I don’t do this because I assumed you initialized this.props.playlistTracks as an empty array. What does his.props.playlistTracks look like if there aren’t any results?
Then maybe my assumption what this.props.playlistTracks and this.props.track.uri are in your App isn’t right.
I wrote the same thing as a function. Then you can compare if the structure is the same: