I am using the Spotify API and want to display only playlists that have a matching playlist ID to the (mock) playlist ID stored in my database.
const [playlistsData, setPlaylistsData] = useState(null);
const [playlists, setPlaylists] = useState(null);
playlist ID stored in my database:
const [myPlaylistId, setMyPlaylistId] = useState(null);
useEffect(() => {
getPlaylistId();
}, []);
const getPlaylistId = async () => {
const response = await fetch("http://localhost:5001/myplaylists");
const id = await response.json();
setMyPlaylistId(id);
};
// returns:
// 0: {id: 1, playlist_id: '34i9Keonvl7HaVKh3Y5S0G'}
// 1: {id: 2, playlist_id: '37i9dQZF1DX4dyzvuaRJ0n'}
Fetching all of the playlists of the current user using API
useEffect(() => {
const fetchData = async () => {
const { data } = await getCurrentUserPlaylists();
setPlaylistsData(data);
};
catchErrors(fetchData());
}, []);
useEffect(() => {
if (!playlistsData) {
return;
}
const fetchMoreData = async () => {
if (playlistsData.next) {
const { data } = await axios.get(playlistsData.next);
setPlaylistsData(data);
}
};
setPlaylists((playlists) => [
...(playlists ? playlists : []),
...playlistsData.items,
]);
// Fetch next set of playlists as needed
catchErrors(fetchMoreData());
}, [playlistsData]);
//Spotify API Call returns (abbreviated)
100:{
collaborative: false
description: ""
id: "37i9dQZF1DX4dyzvuaRJ0n"
}
And the webpage returns:
return (
<main>
<SectionWrapper>
{playlists && <PlaylistsGrid playlists={playlists} />}
</SectionWrapper>
</main>
);
My goal here is to only return the playlists called from Spotify's API that have a matching id to those being called from my database.
I've tried countless potential solves but none have worked. Any help would be greatly appreciated.
CodePudding user response:
setPlaylists((playlists) => [
...(playlists ? playlists : []),
...playlistsData.items,
]);
Here you just have to add below playlist_id in the new array and when you setPlaylists you need to check if the playlistsData.id includes (contains) in the new array
returns:
0: {id: 1, playlist_id: '34i9Keonvl7HaVKh3Y5S0G'}
1: {id: 2, playlist_id: '37i9dQZF1DX4dyzvuaRJ0n'}
Hope this is clear if i have understood your question correctly.
CodePudding user response:
If you are trying to filter two arrays with common element, these are some of the possible solutions i can think of
- use filter and indexOf methods of array
var array = [1,2,3,4];
var anotherOne = [2,4];
var filteredArray = array.filter((el) => anotherOne.indexOf(el) < 0 );
- if you are using lodash.js.
filteredArray = _.difference(array, anotherOne);