Jamming project .... TypeError: Cannot read property 'find' of undefined

I;ve been getting errors left and right, even though i followed the tutorial to a T. So now where Im at is as soon as I want to add a song to a playlist, i get this error:

and here is my code in app.js:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      searchResults: [],
    }
    this.addTrack = this.addTrack.bind(this)
    this.removeTrack = this.removeTrack.bind(this)
    this.updatePlaylistName = this.updatePlaylistName.bind(this)
    this.savePlaylist = this.savePlaylist.bind(this);
    this.search = this.search.bind(this)

  }

  removeTrack(track) {
    var tracks = this.state.playlistTracks;
    tracks = tracks.filter(currentTrack => currentTrack.id !== tracks.id )
    this.setState({playlistTracks: tracks});
  }

  addTrack(track) {
    var tracks = this.state.playlistTracks;
    if (tracks.find(savedTrack => savedTrack.id === track.id)) {
      return

    }
    tracks.push(track);
    this.setState({playlistTracks: tracks})
  }

  updatePlaylistName(name) {
    this.setState({playlistName: name})
  }


  savePlaylist() {
    const trackUris = this.state.playlistTracks.map(track => track.uri)
    Spotify.savePlaylist(this.state.playlistName, trackUris).then(()=> {
      this.setState({playlistName: 'New Playlist', playlistTracks: []
    })
    })

  }

  search(searchTerm) {
    Spotify.search(searchTerm).then(searchResults => {
      this.setState({searchResults: searchResults})
    })
  }
  render () {
    return (
    <div>
  <h1>Ja<span className="highlight">mmm</span>ing</h1>
  <div className="App">
    <SearchBar onSearch={this.search}/> 
    <div className="App-playlist">
       <SearchResults searchResults={this.state.searchResults} onAdd={this.addTrack} />
       <Playlist onNameChange={this.updatePlaylistName} playlistName={this.state.playlistName} playlistTracks={this.state.playlistTracks} onRemove={this.removeTrack} onSave={this.savePlaylist} /> 
    </div>
  </div>
</div>
    )
    }
    
}


export default App;

thanks in advance

Hello, and welcome to the forums!

Since the error is popping up from a function you’re trying to run on this.state.playlistTracks, backtrack to what is supposed to be setting this up and why it might be undefined instead of an array.

Another hint

Double check your constructor. Not for what you have in it, but what you don’t have in it.

Hint 2

In your constructor, you’re setting the initial state of searchResults to an empty array, but not playlistTracks

1 Like