Attempting to troubleshoot the issues causing my React application to malfunction

Having some trouble with my Spotify project. Every time I search for an artist, I receive an error message saying "illegal redirect_uri." I am also facing a list of coding issues that I am struggling to resolve. Any advice or suggestions would be greatly appreciated. Below is the code snippet:

src\Components\SearchBar\SearchBar.js Line 25:5: Duplicate name ‘handleTermChange’ no-dupe-class-members

src\util\Spotify.js Line 1:7: ‘clientId’ is assigned a value but never used no-unused-vars Line 2:7: ‘redirectUri’ is assigned a value but never used no-unused-vars Line 25:31: Unexpected template string expression no-template-curly-in-string Line 31:15: ‘accessToken’ is assigned a value but never used no-unused-vars Line 32:22: Unexpected template string expression no-template-curly-in-string Line 34:27: Unexpected template string expression no-template-curly-in-string Line 57:15: ‘accessToken’ is assigned a value but never used no-unused-vars Line 58:41: Unexpected template string expression no-template-curly-in-string Line 64:13: ‘userId’ is assigned a value but never used no-unused-vars Line 65:27: Unexpected template string expression no-template-curly-in-string Line 72:23: ‘playlistId’ is assigned a value but never used no-unused-vars

import React from 'react';

import './SearchBar.css';

class SearchBar extends React.Component {
    constructor(props) {
        super(props);

        this.state ={
            term: ''
        }

        this.search = this.search.bind(this);
        this.handleTermChange = this.handleTermChange.bind(this);
    }

    search() {
        this.props.onSearch(this.state.term);
    }

    handleTermChange(event) {
        this.setState({term: event.target.value});
    }

    handleTermChange(event) {
        this.setState({term: event.target.value});
    }

    render() {
        return (
            <div className="SearchBar">
  <input onChange={this.handleTermChange} placeholder="Enter A Song, Album, or Artist" />
  <button className="SearchButton" onClick={this.search} >SEARCH</button>
</div>
        )
    }
}

export default SearchBar;
const clientId = '5e56a43c5001426189eda044053e2d30';
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]);
            //This clears the parameters, allowing us to grab a new access token when it expires.
            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(response => {
            return response.json();
        }).then(jsonResponse => {
            if(!jsonResponse.tracks) {
                return [];
            }
            return jsonResponse.tracks.items.map(track => ({
                id: track.id,
                name: track.name,
                artist: track.artists[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;

        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/${user_id}/playlists',
            {
                headers:headers,
                method:'POST',
                body: JSON.stringify({name: name})
            }).then(response => response.json()
            ).then(jsonResponse => {
                const playlistId = jsonResponse.id;
                return fetch('https://api.spotify.com/v1/users/${userId}/playlists',
                {
                    headers: headers,
                    method: 'POST',
                    body: JSON.stringify({Uris: trackUris})
                });
            })
        })
    }
}

export default Spotify;
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 Playlist',
         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)){
      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>Jugglejit!<span className="highlight">ize</span></h1>
  <div className="App">
    <SearchBar onSearch={this.search} /> 
    <div className="App-playlist">
      <SearchResults searchResults={this.state.searchResults}
        onAdd={this.addTrack} /> 
      <Playlist playstName={this.state.playlistName}
        playlistTracks={this.state.playlistTracks} 
        onRemove = {this.removeTrack}
        onNameChange ={this.updatePlaylistName}
        onSave = {this.savePlaylist} /> 
    </div>
  </div>
</div>
    )
  }
}

export default App;

Answer №1

Your Template literals declaration is incorrect; each one must begin and end with a backtick (`)

It should look like this:

const accessUrl = `https://accounts.spotify.com/authorize?client_id=${clientId}&response_type=token&scope=playlist-modify-public&redirect_uri=${redirectUri}`

Use (`) instead of (')

Make sure all your other Template literals follow the same pattern; starting and ending with backticks (`)

return fetch(`https://api.spotify.com/v1/search?type=track&q=${term}`,
Authorization:`Bearer ${accessToken}`

Continue this pattern for all instances...

Additionally, remove one of the handleTermChange functions.

Answer №2

Initially, there are 2 occurrences of handleTermChange. Remove one of them.

Additionally, the usage of Template literals is incorrect. As a result, clientId will not be utilized. Make sure to rectify it as shown below using {``}

const accessUrl = {`https://accounts.spotify.com/authorize?client_id=${clientId}&response_type=token&scope=playlist-modify-public&redirect_uri=${redirectUri}`}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to specifically target header elements within article elements using a CSS selector?

As someone who is not well-versed in CSS, I am looking to target specifically the header elements within article elements. I have some understanding of selectors such as #, ., or ,. article header article, header article.header article#header I believe t ...

Tips for selecting the initial and final elements of a specific class

Here is a simple example of table markup: <div class="table"> <div class="table__headers"></div> <div class="table__row"></div> <div class="table__row"></div> </div& ...

Dropdown element with PrimeNG adorned with a span

I am trying to create a simple form with text inputs and dropdowns. I have successfully implemented the textInput, but I am struggling with the dropdowns. Below is the code that I have so far: <div class="p-grid p-dir-col p-offset-2"> ...

Is the Three.JS camera update causing issues with the shader?

Attempting to replicate the Bubble shader from https://github.com/stemkoski/stemkoski.github.com/blob/master/Three.js/Bubble.html, but encountering issues due to outdated code. The example should refract whatever is behind it, like this: https://i.sstatic ...

The jQuery CSS menu is having trouble highlighting the active link

Can you help me figure out what's wrong with this code and how I can fix it? I'm working on a CSS menu (horizontal) where I want the background and font to change when an item is selected. I found some jQuery code from another post that should m ...

What could be causing my Vue code to behave differently than anticipated?

There are a pair of components within the div. When both components are rendered together, clicking the button switches properly. However, when only one component is rendered, the switch behaves abnormally. Below is the code snippet: Base.vue <templa ...

Acquiring data from a separate Redux slice and utilizing it as the default state in a distinct slice

In my application, I have two Redux slices called userSlice and cartSlice. My goal is to extract the specific value userName from the userSlice and use it as the initial value for a property named user in the cartSlice. Despite my efforts, I am encounterin ...

What could be the reason for the improper display of this?

I am in the process of creating an e-commerce website where users can add products to their virtual shopping carts. However, I am facing an issue with displaying the correct button ('Add to Cart' or 'Remove from Cart') based on whether ...

Updating Variables Declared in Parent Component from a Child Component in React using NextJS - A Comprehensive Guide

After reviewing the tutorial on React: Reverse Data Flow to update the variables foodObj, input, and buttonClicked declared in the Parent Component file Main.js, using the child component <SearchAndSuggestion>, I encountered an issue. Here is a snipp ...

React: You can start the project with npm start successfully, but if you try to build it using npm run build, it throws an EL

My React application, built using create-react-app, has been running smoothly with npm start. A few days ago, I successfully deployed it to Firebase hosting using npm run build. However, today I encountered an issue where npm run build throws the followin ...

What is the method for selecting an item on Material-UI using the tab key?

I'm currently working with the MenuItem component from material-UI. I am attempting to allow users to select an item by pressing the 'tab' key, similar to this: {Object.keys(Countries).map(key => ( <MenuItem key={key} value={Countr ...

Is using float:right making the jquery slide toggle dropdown div (triggered by hover) appear glitchy?

Utilizing jQuery's slidetoggle and hover functions, I have successfully implemented a dropdown feature in my div. Within this div, there is various information displayed including the date, a note counter, and three buttons. The first two are Tumblr ...

Are there any ways to bring visual attention to a GoDaddy template's SEND button using HTML or JS when the original code is unavailable?

I'm currently working on a GoDaddy website using a template that doesn't clearly highlight the SEND button in a Contact Us form. In order to comply with WCAG accessibility standards, active elements must have visible focus indicators. However, si ...

SASS: a common thread connecting multiple applications

The scenario involves a web platform that aggregates various React apps, each with its own .scss files. The goal is to extract the common .scss into a library for convenience. Any suggestions on how best to accomplish this? It's important to note that ...

Advantages of using individual CSS files for components in React.js

As someone diving into the world of Web Development, I am currently honing my skills in React.js. I have grasped the concept of creating Components in React and applying styles to them. I'm curious, would separating CSS files for each React Component ...

Guide on how to preview an uploaded image in React js

Currently, there is a button named image upload that has been created. The goal is to display the selected image after it has been chosen. <GridItem xs={6}> <FormControl className={classes.formControl}> <input ...

Error message "ag-grid: Unable to perform the key.forEach function in the console when resizing columns"

Within the application I am working on, I have implemented the ag-grid view. To address the issue related to the last empty pseudo column, I decided to resize the last displayed column using the 'autoSizeColumns' method of ag-grid. While this sol ...

After completing the Spotify authentication process using implicit grant in a React application, the redirection is not functioning as

I am working on integrating Spotify authentication using the implicit grant method as outlined in their documentation. I have implemented the relevant code into a React component and successfully logged into Spotify. However, I am facing an issue where the ...

Exploring the controller logic in Sails.js index.ejs

I'm struggling to understand how to integrate dynamic logic into the homepage of my Sails.js application. Currently, the homepage is static, but I want to display data on the index.ejs page. I have a MainController with an index function that retrieve ...

What is the correct way to import and display custom fonts (non-google fonts) in a next.js 14 / tailwind combo?

Is there a way to use .otf font files in my next.js 14 project and apply them using tailwind convention? I've noticed that regardless of what I do, the browser defaults to google fonts for the font-family (ui-sans-serif, system-ui, sans-serif, "Apple ...