Search code examples
reactjsasync-awaitspotify

Calling an Async function in React without clicking a button?


I'm working on a Spotify integration app, and I have the following code within the main function of the App. This code basically lets you log in through Spotify, and then upon being redirected to my app's page, you click a button that gets your top artists for a given time period from your Spotify data. I have included the code that I have a question about below:

***SOME CODE***

const getTopTracks = async (e) => {
        e.preventDefault()
        const {data} = await axios.get("https://api.spotify.com/v1/me/top/artists", {
            headers: {
                Authorization: `Bearer ${token}`
            },
            params: {
                limit: 10, 
                time_range: "short_term"
            }
        })
        console.log(data);
        setArtists(data.items);
    }

***SOME MORE CODE***

return (
        <div className="App">
            <header className="App-header">
                <h1>monk<span className='smaller'>media</span>
                </h1>
                    {!token ?
                    <a href={`${AUTH_ENDPOINT}?client_id=${CLIENT_ID}&redirect_uri=${REDIRECT_URI}&response_type=${RESPONSE_TYPE}&scope=${SCOPE}`}>Login to Spotify</a>
                    : <button className='logout' onClick={logout}> Logout </button>} 

                    {token ?
                        <form onSubmit={getTopTracks}>
                            <input type="text" onChange={e => setSearchKey(e.target.value)}/>
                            <button type={"submit"}>GET MY TOP ARTISTS</button>
                        </form>
                    

                        : <h2>Please login ^</h2>
                    }

                    {renderArtists()} //prints artists
                </header>
        </div>
    );
}

I had followed a tutorial to create an app that allows you to search for artists through the Spotify Api, so I used some of that code here, which is why there is a form and a button to get your top artists. However, I'd like top artists to appear upon being redirected to my app after successfully logging in through Spotify, and I don't want there to be a button you have to push.

I tried removing the form, and just calling getTopTracks in the return statement, but then the Spotify Api call wouldn't work. I think it has something to do with the async function, but I'm not sure how to solve this problem. How can I remove the form and make it so the "getTopTracks" function is called immediately upon returning to my web app after logging in?

Any help would be appreciated!


Solution

  • You can call useEffect for this:

    useEffect(() => {
      const getTopTracks = async () => {
        const { data } = await axios.get(
          "https://api.spotify.com/v1/me/top/artists",
          {
            headers: {
              Authorization: `Bearer ${token}`,
            },
            params: {
              limit: 10,
              time_range: "short_term",
            },
          }
        );
        console.log(data);
        setArtists(data.items);
      };
      getTopTracks();
    }, []);
    

    I also highly recommend reading this article.