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,
2
Answers
Create a function that checks if the song already exist in
localStorage
by passingsongName
as a parameter.and before saving to
localStorage
just run the function to do the action based on the return value of the functionlocalStorage
can only store strings, so you have to convert your list of songs to JSON every time it is saved tolocalStorage
and then convert it back to a JavaScript array every time you want to check if a specific song has been saved.You can do something like this:
If you are concerned about performance you can load the list of songs into the memory when the program launches and then operate on that list, so you don’t have to call
JSON.parse()
every time you have to check if a song has been saved. Additionally, you can use a map where keys are URLs, so you don’t have to iterate over the entire list every time.