The object has an array of objects
songs = {"items": [{...},{...}]};
After mapping and filling this array with values from api calls, I can console log and see all the items I want store in that array, but when I use this array in another function or log the array size, in both cases the array is empty.
I know this issue is related to the api calls and asynchronicity, but I couldn't solve it.
The context code:
const getArrayOfSongs = (playlists, dataFavorites, dataProfile, accessToken) => {
let songs = {"items": []};
playlists.map((playlist) => {
axios
.get(PLAYLIST_ENDPOINT + playlist.id + "/tracks?limit=50&offset=0", {
headers: {
Authorization: "Bearer " + accessToken,
},
})
.then((response) => {
response.data.items.map((song) => {
if (song.track.is_local === false) {
let artists = [];
const cutArtist = () => { song.track.artists.forEach((artist) => artists.push(artist.name)) }
cutArtist();
const obj = { "name": song.track.name, "id": song.track.id, "album": song.track.album.name, "artist": artists, "link": song.track.href };
const index = songs.items.findIndex(object => object.id === obj.id);
if (index === -1) {
songs.items.push(obj);
}
}
});
})
.catch((error) => {
console.log(error);
});
});
//shows me everything
console.log(songs.items)
//shows me 0 value
console.log(songs.items.length)
const user = getProfile(dataProfile);
//array is empty
sendSongs(JSON.stringify(songs), user);
}