Next.js Discord

Discord Forum

API Issue

Answered
Whiskered Tern posted this in #help-forum
Open in Discord
Whiskered TernOP
Hi, I'm building a website that displays my current song on Spotify. This is my code. However, I keep getting this error every time i refresh. Can someone help me please?
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.


Code:
import React, { useState, useEffect } from "react"
import axios from "axios"

const Spotify = () => {
  const [token, setToken] = useState("")
  const [song, setSong] = useState("")
  const [isPlaying, setIsPlaying] = useState(false)

  useEffect(() => {
    let storedToken = window.localStorage.getItem("token")
    setToken(
      "4fxl17hBnoAcFhh-VWvbCQD[redacted]"
    )

    // Set up interval for automatic song fetching
    const intervalId = setInterval(() => {
      getSong()
    }, 1000)

    // Clean up the interval when the component is unmounted
    return () => clearInterval(intervalId)
  }, [token])

  const getSong = async () => {
    try {
      const { data } = await axios.get(
        "https://api.spotify.com/v1/me/player/currently-playing",
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        }
      )

      setSong(data.item.name)
      setIsPlaying(data.is_playing)
      console.log(data.is_playing)
    } catch (error) {
      console.error("Error fetching currently playing track:", error)
    }
  }

  const displaySong = () => {
    return <div>{isPlaying ? song : "Currently Not Playing..."}</div>
  }

  return <div>{displaySong()}</div>
}

export default Spotify
Answered by Whiskered Tern
i just had to restart the server
View full answer

7 Replies

Try to change your initialization to „function“ instead of const
Peterbald
Try to change your return part as a "return (<div>{displaySong}</div>);"
@Whiskered Tern solved?
Whiskered TernOP
yeah haha
turns out nothing was wrong
Whiskered TernOP
i just had to restart the server
Answer
Whiskered TernOP
thanks for the help!