Jamming step 95

Hey There,

Stuck again. I reviewed the video 2 times and tried to double check each step. but I can not find the issue. When I type in the search bar the artist name it does not show anything. there are also no visible errors.

Here is my Sportify.js code

const clientId = "";
const redirectURI = "http://localhost:3000/";
let accessToken;

const Spotify = {
	getAccessToken() {
		if (accessToken) {
			return accessToken;
		}
		//check for access token match
		const accessTokenMatch = window.location.href.match(/access_token=([^&]*)/);
		const expiresInMatch = window.location.href.match(/expires_in=([^&]*)/);

		if (accessTokenMatch && expiresInMatch) {
			accessToken = accessTokenMatch[1];
			const expiresIn = Number(expiresInMatch[1]);
			window.setTimeout(() => (accessToken = ""), expiresIn * 1000);
			window.history.pushState("Access Token", null, "/");
			return accessToken;
		} else {
			const accessUrl = `https://accounts.spotify.com/authorize?client_id=${clientId}&response_type=token&scope=playlist-modify-public&redirect_uri=${redirectURI}`;
			window.location = accessUrl;
		}
	},

	search(term) {
		const accessToken = Spotify.getAccessToken();
		return fetch(`https://api.spotify.com/v1/search?type=track&q=${term}`, {
			headers: { Authorization: `Bearer ${accessToken}` },
		})
			.then((res) => {
				return res.json();
			})
			.then((jsonRes) => {
				if (!jsonRes.tracks) {
					return [];
				}
				return jsonRes.tracks.items.map((track) => ({
					id: track.id,
					name: track.name,
					artist: track.artist[0].name,
					album: track.album.name,
					uri: track.uri,
				}));
			});
	},

	savePlaylist(playListName, arrayOfTrackURI) {
		if (!playListName || !arrayOfTrackURI.length) {
			return;
		}
		const accessToken = Spotify.getAccessToken();
		const headers = { Authorization: `Bearer ${accessToken}` };
		let userId;
		return fetch("https://api.spotify.com/v1/me", { headers: headers })
			.then((response) => response.json())
			.then((jsonResponse) => {
				userId = jsonResponse.id;
				return fetch(`https://api.spotify.com/v1/users/${userId}/playLists`, {
					headers: headers,
					method: "POST",
					body: JSON.stringify({ name: playListName }),
				})
					.then((response) => response.json())
					.then((jsonResponse) => {
						const playListId = jsonResponse.id;
						return fetch(
							`https://api.spotify.com/v1/users/${userId}/playlists/${playListId}/tracks`,
							{
								headers: headers,
								method: "POST",
								body: JSON.stringify({ uris: arrayOfTrackURI }),
							}
						);
					});
			});
	},
};

export default Spotify;

Here is App.js code:

import React from "react";
import "./App.css";

import SearchBar from "../SearchBar/SearchBar";
import SearchResults from "../SearchResults/SearchResults";
import Playlist from "../PlayList/PlayList";

import Spotify from "../../util/Spotify";

class App extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			searchResults: [],
			playListName: "My play list",
			playListTracks: [],
		};
		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);
	}

	addTrack(track) {
		let tracks = this.state.playListTracks;

		if (tracks.find((savedTrack) => savedTrack.id === track.id)) {
			console.log(track.id);
			console.log(track);
			return;
		}
		tracks.push(track);
		this.setState({ playListTracks: tracks });
	}

	removeTrack(track) {
		let tracks = this.state.playListTracks;

		tracks = tracks.filter((currentTrack) => currentTrack.id !== track.id);
		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(term) {
		Spotify.search(term).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
							playListName={this.state.playListName}
							playListTracks={this.state.playListTracks}
							onRemove={this.removeTrack}
							onNameChange={this.updatePlayListName}
							onSave={this.savePlayList}
						/>
					</div>
				</div>
			</div>
		);
	}
}

export default App;

When I click on search no results.

When I click on SAVE TO SPOTIFY button it throws an error to me

I understand it is related to one of the .then() methods. But I can not understand why and which.

Please help.
thanks in advance
Regards

Hi,

The issue that you’re not getting anything back from Spotify when you type an artist’s name rather than a track’s name is that you’re not requesting it from Spotify:

‘Cannot read properties of ‘undefined’’ refers to the object a method is applied to – not the method itself. That means that the problem can be found within your Spotify.savePlaylist method. Possible causes for that can be:

  1. The method isn’t imported correctly
  2. It isn’t found due to misspelling
  3. It doesn’t return anything valid (console.log the returned values inside the Spotify.savePlaylist method in order to see whether it logs anything in the first place. If it does it would mean that 1 and 2 aren’t the case. If it does, does it log anything truthy?)
  4. It does not return a promise.

Hi @mirja_t,

Sorry for the long delay. Procrastinated.

I tried to console.log in Spotify.js file and App.js savePlaylist method . Result of SPotify.js method console No output. App.js savePlaylist gave me some out.

Please see below both file’s code with console logs and the outputs screenshots:

I have no idea what is wrong.

Please help.

regards,

App.js


import React from "react";
import "./App.css";

import SearchBar from "../SearchBar/SearchBar";
import SearchResults from "../SearchResults/SearchResults";
import Playlist from "../PlayList/PlayList";

import Spotify from "../../util/Spotify";

class App extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			searchResults: [],
			playListName: "My play list",
			playListTracks: [],
		};
		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);
	}

	addTrack(track) {
		let tracks = this.state.playListTracks;

		if (tracks.find((savedTrack) => savedTrack.id === track.id)) {
			console.log(track.id);
			console.log(track);
			return;
		}
		tracks.push(track);
		this.setState({ playListTracks: tracks });
	}

	removeTrack(track) {
		let tracks = this.state.playListTracks;

		tracks = tracks.filter((currentTrack) => currentTrack.id !== track.id);
		this.setState({ playListTracks: tracks });
	}

	updatePlayListName(name) {
		this.setState({ playListName: name });
	}

	savePlayList() {
		const trackURIs = this.state.playListTracks.map((track) =>
			console.log("Track", track.uri)
		);
		console.log("trackUris", trackURIs);
		console.log("Spotify", Spotify);

		Spotify.savePlaylist(this.state.playListName, trackURIs).then(() => {
			console.log("PLAYLIST", this.state.playListName);
			console.log("TRACK URIS", trackURIs);
			// this.setState({ playListName: "New Playlist", playListTracks: [] });
			console.log(
				this.setState({ playListName: "New Playlist", playListTracks: [] })
			);
		});
	}

	search(term) {
		Spotify.search(term).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
							playListName={this.state.playListName}
							playListTracks={this.state.playListTracks}
							onRemove={this.removeTrack}
							onNameChange={this.updatePlayListName}
							onSave={this.savePlayList}
						/>
					</div>
				</div>
			</div>
		);
	}
}

export default App;


Spotify.js

const clientId = "";
const redirectURI = "http://localhost:3000/";
let accessToken;

const Spotify = {
	getAccessToken() {
		if (accessToken) {
			return accessToken;
		}
		//check for access token match
		const accessTokenMatch = window.location.href.match(/access_token=([^&]*)/);
		const expiresInMatch = window.location.href.match(/expires_in=([^&]*)/);

		if (accessTokenMatch && expiresInMatch) {
			accessToken = accessTokenMatch[1];
			const expiresIn = Number(expiresInMatch[1]);
			window.setTimeout(() => (accessToken = ""), expiresIn * 1000);
			window.history.pushState("Access Token", null, "/");
			return accessToken;
		} else {
			const accessUrl = `https://accounts.spotify.com/authorize?client_id=${clientId}&response_type=token&scope=playlist-modify-public&redirect_uri=${redirectURI}`;
			window.location = accessUrl;
		}
	},

	search(term) {
		const accessToken = Spotify.getAccessToken();
		return fetch(`https://api.spotify.com/v1/search?type=track&q=${term}`, {
			headers: { Authorization: `Bearer ${accessToken}` },
		})
			.then((res) => {
				return res.json();
			})
			.then((jsonRes) => {
				if (!jsonRes.tracks) {
					return [];
				}
				return jsonRes.tracks.items.map((track) => ({
					id: track.id,
					name: track.name,
					artist: track.artist[0].name,
					album: track.album.name,
					uri: track.uri,
				}));
			});
	},

	savePlaylist(name, trackUris) {
		if (!name || !trackUris.length) {
			return;
		}
		const accessToken = Spotify.getAccessToken();
		const headers = { Authorization: `Bearer ${accessToken}` };
		let userId;
		console.log("Access token", accessToken);
		console.log("Headers", headers);
		return fetch(
			"https://api.spotify.com/v1/me",
			console.log({ headers: headers })
		)
			.then((response) => console.log(response.json()))
			.then((jsonResponse) => {
				userId = jsonResponse.id;
				console.log("userID", userId);
				return fetch(`https://api.spotify.com/v1/users/${userId}/playLists`, {
					headers: headers,
					method: "POST",
					body: JSON.stringify({ name: name }),
				})
					.then((response) => response.json())
					.then((jsonResponse) => {
						const playListId = jsonResponse.id;
						console.log("PLayList", playListId);
						return fetch(
							`https://api.spotify.com/v1/users/${userId}/playlists/${playListId}/tracks`,
							{
								headers: headers,
								method: "POST",
								body: JSON.stringify({ uris: trackUris }),
							}
						);
					});
			});
	},
};

export default Spotify;



Hi,
did you create your app with the command line npx create-react-app jammming? I did and this is the error I get:
Bildschirmfoto 2021-11-04 um 22.33.46
It tells you exactly where the error is.
Comment out the return value and return an empty array instead in order to avoid the error message.
Then log the first result you get from Spotify:

console.log(jsonRes.tracks.items[0])

That shows you how the values can be accessed and how you must write it.