I’m trying to use Last.fm’s API to find similar songs given a song name. Last.fm has a feature that can do this called track.getSimilar, but both “track” and “artist” are required parameters. However, because of the way this works, I can’t figure out a way to either a) get both a song name, and the artist from one search bar input, or b) get the song’s artist using track.search. Here’s the part of my code relating to this:
useEffect(() => {
fetch(`${API_GET_SIMILAR_URL}&page=${RESULT_PAGE}&artist=${DEFAULT_ARTIST}&track=${DEFAULT_TRACK}`)
.then(response => response.json())
.then(jsonResponse => {
const tracks = jsonResponse.similartracks[Object.keys(jsonResponse.similartracks)[0]];
dispatch({
type: "SEARCH_SUCCESS",
payload: tracks
});
});
}, []);
const search = (searchValue) => {
dispatch({
type: "SEARCH_REQUEST"
});
fetch(`${API_GET_SIMILAR_URL}&page=${RESULT_PAGE}&track=${searchValue}`)
.then(response => response.json())
.then(jsonResponse => {
if (!jsonResponse.error) {
const tracks = jsonResponse.similartracks[Object.keys(jsonResponse.similartracks)[0]];
dispatch({
type: "SEARCH_SUCCESS",
payload: tracks
});
} else {
dispatch({
type: "SEARCH_FAILURE",
error: jsonResponse.error
});
}
});
};
let {
tracks,
errorMessage,
loading
} = state;
console.log(state);
In my search function I’m getting an Uncaught (in promise) TypeError: Cannot convert undefined or null to object
error in the Object.keys line because I’m not using the artist parameter when calling the API. I tried using track.search to get the artist but I’m not sure where/how to incorporate it into my code.
I appreciate any help or advice. Thanks.