英文:
localStorage | Checking if a value exists before setting it
问题
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 thousands of songs, so it should iterate over the array "songs" and find if there's a matching "url".
英文:
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,
答案1
得分: 2
function isSongSaved(songName) {
const songs = localStorage.getItem("songs") !== null ? JSON.parse(localStorage.getItem("songs")) : [];
// Checking each object from songs
for (let i = 0; i < songs.length; i++) {
if (songs[i]?.songName === songName) {
return true; // return immediately when finding that the song exists
}
}
return false; // song doesn't exist
}
and before saving to localStorage
just run the function to do the action based on the return value of the function.
英文:
Create a function that checks if the song already exist in localStorage
by passing songName
as a parameter.
function isSongSaved(songName) {
const songs = localStorage.getItem("songs") !== null ? JSON.parse(localStorage.getItem("songs")) : [];
// Checking each object from songs
for (let i = 0; i < songs.length; i++) {
if (songs[i]?.songName === songName) {
return true; // return immediately when finding that the song exists
}
}
return false; // song doesn't exist
}
and before saving to localStorage
just run the function to do the action based on the return value of the function
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);
// Only saving to localStorage if it doesn't exist
if (!isSongSaved(userData.songName)) {
localStorage.setItem("songs", JSON.stringify(songs));
}
navigate("/");
});
答案2
得分: 0
localStorage
只能存储字符串,因此每次保存到 localStorage
时,您必须将歌曲列表转换为 JSON,然后在需要检查是否已保存特定歌曲时,将其转换回 JavaScript 数组。
您可以这样做:
const songs = JSON.parse(localStorage.getItem("songs") || "[]");
const isAlreadySaved = songs.some(song => song.url === targetUrl);
如果您担心性能问题,您可以在程序启动时将歌曲列表加载到内存中,然后对该列表进行操作,这样您就不必每次都调用 JSON.parse()
来检查歌曲是否已保存。此外,您可以使用一个映射,其中键是URL,这样您不必每次都遍历整个列表。
英文:
localStorage
can only store strings, so you have to convert your list of songs to JSON every time it is saved to localStorage
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:
const songs = JSON.parse(localStorage.getItem("songs") || "[]")
const isAlreadySaved = songs.some(song => song.url === targetUrl)
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论