spotify / web-api-examples

Basic examples to authenticate and fetch data using the Spotify Web API
Apache License 2.0
1.96k stars 1.64k forks source link

Unhandled Rejection (TypeError): Cannot read property 'name' of undefined #42

Open davidryan-mu opened 4 years ago

davidryan-mu commented 4 years ago

Hi folks,

Trying to follow this tutorial: https://www.youtube.com/watch?v=prayNyuN3w0 using this web api. I'm having an issue where my response after calling getMyCurrentPlaybackState(). All of the authorization stuff is working. Here is the code:

import React, { Component } from 'react';
import P5Wrapper from 'react-p5-wrapper';
import sketch from './sketch';

import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import Button from 'react-bootstrap/Button';

import Spotify from 'spotify-web-api-js';

const spotifyWebAPI = new Spotify();

export default class App extends Component {
  constructor(props) {
    super(props);
    const params = this.getHashParams();
    this.state = {
      loggedIn: params.access_token ? true: false,
      nowPlaying: {
        name: "Not Checked",
        image: ""
      }
    }
    if(params.access_token) {
      spotifyWebAPI.setAccessToken(params.access_token);
    }
  }

  getHashParams() {
    var hashParams = {};
    var e, r = /([^&;=]+)=?([^&;]*)/g,
        q = window.location.hash.substring(1);
    while ( e = r.exec(q)) {
       hashParams[e[1]] = decodeURIComponent(e[2]);
    }
    return hashParams;
  }

  getNowPlaying() {
    spotifyWebAPI.getMyCurrentPlaybackState()
      .then((response) => {
        this.setState({
          nowPlaying: {
            name: response.item.name,
            image: response.item.album.images[0]
          }
        })
      })
  }

  render() {
      return (
        <div className="App">
          <h1>Spotify Visualizer</h1>

          <Button variant="success" size="lg" href="http://localhost:8888">Login With Spotify</Button>

          <div>
            Now Playing: {this.state.nowPlaying.name}
          </div>

          <div>
            <img src={this.state.nowPlaying.image} style={{width: "100px"}}/>
          </div>

          <Button variant="outline-success" onClick={() => this.getNowPlaying()}>Currently Playing</Button>
        </div>
      );
  }
}

Any help would be greatly appreciated!

Sealra commented 3 years ago

Did you resolve it? i have the same problem right now haha

kaelens commented 3 years ago

for any future reference: https://stackoverflow.com/questions/62393355/how-to-handle-response-item-is-undefined this should work!