Brandon Powell Brandon Powell - 1 year ago 104
Javascript Question

ReactJS componentDidMount, Fetch Spotify API and Promise

I'm learning how used ReactJS, Spotify API, and Promise. I'm trying to fetch musician top albums on Spotify and play 30 seconds of the track.

I'm using a Spotify package called spotify-web-api-node I think I'm not understanding something fundamental about React or JS.

Syntax error: Unexpected token, expected ( (11:8)


import React from 'react';

import SpotifyWebApi from 'spotify-web-api-node';
require('dotenv').config();


export default class SpotifyComponent extends React.Component {
// Create the api object with the credentials
const spotifyApi = new SpotifyWebApi({
clientId : process.env.REACT_APP_SPOTIFY_CLIENT_ID,
clientSecret : process.env.REACT_APP_SPOTIFY_CLIENT_SECRET
});
// Save the access token so that it's used in future calls
componentDidMount() {
**(11:8)** --> return spotifyApi = new Promise((resolve, reject) => {
spotifyApi.clientCredentialsGrant()

.then( => (data) {
console.log('The access token expires in ' + data.body['expires_in']);
console.log('The access token is ' + data.body['access_token']);
});

// using Promises through Promise, Q or when - get Elvis' albums in range [20...29]
spotifyApi.getArtistAlbums('43ZHCT0cAZBISjO8DG9PnE', {limit: 10, offset: 20})
.then(function(data) {
console.log('Album information', data);
}, function(err) {
console.error(err);
});
});

SpotifyWebApi.setPromiseImplementation(Q);
}
}

Answer Source

You can't have a const definition inside of a class like that.

You should either move it outside or remove the const:

// Create the api object with the credentials
const spotifyApi = new SpotifyWebApi({
  clientId : process.env.REACT_APP_SPOTIFY_CLIENT_ID,
  clientSecret : process.env.REACT_APP_SPOTIFY_CLIENT_SECRET
});

export default class SpotifyComponent extends React.Component {

or

export default class SpotifyComponent extends React.Component {
  // Create the api object with the credentials
  spotifyApi = new SpotifyWebApi({
    clientId : process.env.REACT_APP_SPOTIFY_CLIENT_ID,
    clientSecret : process.env.REACT_APP_SPOTIFY_CLIENT_SECRET
  });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download