I'm doing a React app where I'm using Last FM API. App shows current track if music is playing or if it's not it shows last listened track. At this point everything works just fine. My problem is I want to show if I'm currently listening or not, but just don't know how. I tried to scroll through documentation but didn't really find anything helpful.
I'm fetching data from here: https://ws.audioscrobbler.com/2.0/?method=user.getRecentTracks&user=${userName}&api_key=${apiKey}&format=json
const track = scrobbles?.recenttracks?.track;
const [
{ name: songName, artist: { '#text': artistName } = {}}
= {}] = track;
return (
<div>
<h1>playing</h1>
<h3>{songName}</h3>
<h3>{artistName}</h3>
</div>
)
scrobbles is variable where all of JSON data is stored. In JSON data there is nowplaying attribute inside track array which returns boolean value, I just don't know how to use that value.
I found this link which shows stored JSON data: https://lastfm-docs.github.io/api-docs/user/getRecentTracks/
I'd like to have probably some kind of conditional statement around that h1 element which shows playing or not playing.
Any ideas how to do that? Thanks
Just found solution for this. This probably isn't best or most beautiful solution but it works.
const track = scrobbles?.recenttracks?.track
if (track.length > 0) {
const trarray = track[0];
if (trarray['@attr'] && trarray['@attr']['nowplaying']) {
return (
<div>
<h1>Playing</h1>
</div>
)
}
}
return (
<div>
<h1>Not playing</h1>
</div>
)