I'm very new to Javascript/web dev and attempting to pull data from the Spotify API to use in a website. Performing two separate queries to pull the data I need, and trying to combine the two response.json objects using
const data = Object.assign(source, target).
However, when I do so, only the second object (target) gets assigned to data and shows up in my web app. I believe the first entry in data2 is identical to the last entry in data1 (key, value), not sure if this might be causing the issue, but from what I've read, data2 should just override that entry in data1. Considering keeping these response objects separate and just trying to combine the data in a further step (combining two maps), but not quite sure the correct syntax to use for this process as I keep getting errors there too. Any help would would be greatly appreciated! Code below.
const fetchTopSongs = async (duration) => {
const response1 = await window.fetch('https://api.spotify.com/v1/me/top/tracks?' +
querystring.stringify({
limit: 50,
offset: 0,
time_range: duration,
}), {
method: 'GET',
headers: {
Authorization: 'Bearer ' + accessToken,
},
});
const data1 = await response1.json()
const response2 = await window.fetch('https://api.spotify.com/v1/me/top/tracks?' +
querystring.stringify({
limit: 50,
offset: 49,
time_range: duration,
}), {
method: 'GET',
headers: {
Authorization: 'Bearer ' + accessToken,
},
});
const data2 = await response2.json()
const data = Object.assign(data1,data2)
// const map1 = data1.items.map(song => song.name)
// const map2 = data2.items.map(song => song.name)
// const map = new Map([...map1,...map2])
// setTopSongs(map)
setTopSongs(data.items.map(song => song.name))
}
It will be good to have an example of the response, but based on the search api
It looks like the response is something like:
{
"tracks": {
href: foo,
items: [],
total: bar
}
}
Said that, I think you need to merge the items
array
const result = [...data1.items, ...data2.items]