37
loading...
This website collects cookies to deliver better user experience
http://localhost:3000
and confirm by clicking on add, then save the settings.npx create-react-app spotify-react
cd spotify-react && yarn start
you jump into the projects directy and start the development server which then runs at http://localhost:3000
by default.(If for whatever reason the port is not 3000 make sure to change the redirect url in your spotify app settings.)
App.js
and remove all that stuff you don't need, so you app will look similiar to this:import './App.css';
function App() {
return (
<div className="App">
<header className="App-header">
</header>
</div>
);
}
export default App;
(You get the CLIENT_ID
from the Spotify App Overview, mentioned at the beginning.)
const CLIENT_ID = "+++++++++++++++++++++++++++++"
const REDIRECT_URI = "http://localhost:3000"
const AUTH_ENDPOINT = "https://accounts.spotify.com/authorize"
const RESPONSE_TYPE = "token"
App.js
which looks like this:<a href={`${AUTH_ENDPOINT}?client_id=${CLIENT_ID}&redirect_uri=${REDIRECT_URI}&response_type=${RESPONSE_TYPE}`}>Login to Spotify</a>
localhost:3000
.access token
which we need to authorize the API calls.useEffect
from react.hash
and extract the token
by performing some tasks. After that we store the token in a state variable with help of the useState
hook as well as we save the token in our localeStorage.useEffect
as well as the useState
hook to your application.import {useEffect, useState} from 'react';
const [token, setToken] = useState("")
useEffect(() => {
const hash = window.location.hash
let token = window.localStorage.getItem("token")
if (!token && hash) {
token = hash.substring(1).split("&").find(elem => elem.startsWith("access_token")).split("=")[1]
window.location.hash = ""
window.localStorage.setItem("token", token)
}
setToken(token)
}, [])
hash
or we already have a token saved in our localStorage. We substring the hash at the beginning. We split the String by the ampersands. Then we search vor that element which contains access_token
. This element than again will be split at the equal sign. The array we get contains the token at index 1.
const logout = () => {
setToken("")
window.localStorage.removeItem("token")
}
App.js
should now look like thisfunction App() {
const CLIENT_ID = "+++++++++++++++++++++++++++++"
const REDIRECT_URI = "http://localhost:3000"
const AUTH_ENDPOINT = "https://accounts.spotify.com/authorize"
const RESPONSE_TYPE = "token"
const [token, setToken] = useState("")
useEffect(() => {
const hash = window.location.hash
let token = window.localStorage.getItem("token")
if (!token && hash) {
token = hash.substring(1).split("&").find(elem => elem.startsWith("access_token")).split("=")[1]
window.location.hash = ""
window.localStorage.setItem("token", token)
}
setToken(token)
}, [])
const logout = () => {
setToken("")
window.localStorage.removeItem("token")
}
return (
<div className="App">
<header className="App-header">
<h1>Spotify React</h1>
{!token ?
<a href={`${AUTH_ENDPOINT}?client_id=${CLIENT_ID}&redirect_uri=${REDIRECT_URI}&response_type=${RESPONSE_TYPE}`}>Login
to Spotify</a>
: <button onClick={logout}>Logout</button>}
</header>
</div>
);
}
export default App;
const [searchKey, setSearchKey] = useState("")
const [artists, setArtists] = useState([])
axios
which will handle our HTTP request with following commandyarn add axios
import axios from 'axios";
searchArtists
function. We use axios to perform the GET
request to the spotify API endpoint. As request configuration we pass an object which contains the header with the Bearer Authorization and the token. As well as a params object containing the search term and the type of search which is here set to artist
.const searchArtists = async (e) => {
e.preventDefault()
const {data} = await axios.get("https://api.spotify.com/v1/search", {
headers: {
Authorization: `Bearer ${token}`
},
params: {
q: searchKey,
type: "artist"
}
})
setArtists(data.artists.items)
}
<form onSubmit={searchArtists}>
<input type="text" onChange={e => setSearchKey(e.target.value)}/>
<button type={"submit"}>Search</button>
</form>
renderArtists
function and call it inside the return of our App.js
.const renderArtists = () => {
return artists.map(artist => (
<div key={artist.id}>
{artist.images.length ? <img width={"100%"} src={artist.images[0].url} alt=""/> : <div>No Image</div>}
{artist.name}
</div>
))
}
{renderArtists()}