I'm supposed to paste a youtube link into a form, and eventually, it'll add some information to the localStorage under the key "songs".
My question is - how can I check if this link has been already added (and if so, I'll add a notification that says it already exists)?
This is what I have in localStorage:
- In the localStorage I have an array of "songs".
- "songs" are objects that have values of - url, songName, songThumbnail.
Is there a way to access a specific value (let's say the url) to check if it exists?
Please note that it is possible to have tens or thousand of songs, so it should iterate over the array "songs" and find it there's a matching "url".
const send = (userData:Song) => {
let songs : Song[] = [];
const songIdentifier = userData.url.split("=")[1];
axios.get(`https://www.googleapis.com/youtube/v3/videos?part=snippet&id=${songIdentifier}&fields=items(id%2Csnippet)&key=${apiKey}`).then(response => {
setImg(response.data.items[0].snippet.thumbnails.default.url);
setSongName(response.data.items[0].snippet.title);
userData.songImg = response.data.items[0].snippet.thumbnails.default.url;
userData.songName = response.data.items[0].snippet.title;
songs = localStorage.getItem("songs") ? JSON.parse(localStorage.getItem("songs")) : [];
songs.push(userData);
localStorage.setItem("songs", JSON.stringify(songs));
navigate("/");
});
I added a screenshot of what's inside the key "songs".
enter image desciption here - this is the screenshot of "songs" values,
Create a function that checks if the song already exist in
localStorageby passingsongNameas a parameter.and before saving to
localStoragejust run the function to do the action based on the return value of the function