Skip to content
Advertisement

Calling async function in .map() (React)

I’m trying to iterate over IDs (track.id) and for each of them fetch some data (based on those IDs) from API (getBPM()). I’m pretty sure it’s connected with Promises and I’m not very fluent with these yet. Here’s the code:

const getBpm = async (id) => {
    const {data} = await axios.get("https://api.spotify.com/v1/audio-features", {
        headers: {
            Authorization: `Bearer ${token}`
        },
        params: {
            ids: id,
        }
    }).catch((error) => {
        console.log(error);
    })
    return Math.round(data[0]?.audio_features[0].tempo);
}

function renderTracks() {
        return tracks?.map((track) => 
            <li key={track.id} className="song-item">
                <a className='link-to-song' href="">
                    <div className="img-with-data">
                    <img src={track.album.images[0].url} alt="" />
                        <div className="title-artist">
                            <p className='song-title'>{track.name}</p>
                            <p className='song-artist'>{track.artists[0].name}</p>
                        </div>
                    </div>
                    <p className="tempo">{getBpm(track.id)}</p>
                </a>
            </li>
        )
}

I’ve tried some things, but couldn’t get it to work. I’d appreciate any kind of help

Advertisement

Answer

When you call an async function you have to await the the function like await getBpm(track.id). Ideally you shouldn’t fetch the data in the return statement. the spotify API allows you to fetch multiple tracks on each request. https://developer.spotify.com/console/get-audio-features-several-tracks/ I would do something like

const songIds = tracks.map(track => track.id).join(","); // songIds should be a string of track ID's separated by a comma (if my code errors, you know what to do)
const trackDataFromApi = await getBpm(songIds); // This will give you data for all your songs 

Then you might want to merge your 2 data sets. And add your tempo-data to your tracks-variable.

And your function.

const getBpm = async (ids) => {
    const {data} = await axios.get("https://api.spotify.com/v1/audio-features", {
        headers: {
            Authorization: `Bearer ${token}`
        },
        params: {
            ids: ids, // or just ids for shorthand
        }
    }).catch((error) => {
        console.log(error);
    })
    return data;
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement