0
search(term) {
        //Spotify.getAccessToken() will RETURN accessToken from previous method.
        const accessToken = Spotify.getAccessToken();
        
        //Remember to RETURN the fetch
        return fetch(`https://api.spotify.com/v1/search?type=track&q=${term}`, {
            headers: {
                'Authorization': `Bearer ${accessToken}`
            }
        })
        .then(response => {
            if (response.ok) {
                console.log(response);
                return response.json;
            };
            throw new Error('Request failed!');
        }, networkError => {
            console.log(networkError.message);
        })
        .then(jsonResponse => {
            if (!jsonResponse.tracks) {
                return [];
            };
            return jsonResponse.tracks.items.map(track => ({
                    id: track.id, 
                    name: track.name,
                    artists: track.artists[0].name,
                    album: track.album.name,
                    uri: track.uri

            }));
        });
    }

In this method, when I send the GET request, the console logs the initial response, but when I check the actual content of the response it is empty and doesn't contain any tracks. Yet, when I type the end point url (specified in fetch()), I can see the results in the browser. I've been trying to find a solution for a few hours but I can't see what I'm doing wrong.

Thanks.

1 Answer 1

1

chain a .catch on the promise and console the error, oh and btw you should return a response.json() like a function from there not just response.json

Sign up to request clarification or add additional context in comments.

2 Comments

Damn, such a simple solution for a problem that consumed hours of my time haha. Thank you. What do you mean by .catch() - why is it necessary if I throw a new Error previously?
Well catch is made to capture the errors that are thrown, a catch on this promise would describe whatever errors you throw or has been thrown from the promise. They are not required but will give you some information for errors that happened while resolving the promise

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.