localStorage | 在设置值之前检查其是否存在

huangapple go评论62阅读模式
英文:

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(&quot;songs&quot;) !== null ? JSON.parse(localStorage.getItem(&quot;songs&quot;)) : [];
  // Checking each object from songs
  for (let i = 0; i &lt; songs.length; i++) {
    if (songs[i]?.songName === songName) {
        return true; // return immediately when finding that the song exists
    }
  }
  return false; // song doesn&#39;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&amp;id=${songIdentifier}&amp;fields=items(id%2Csnippet)&amp;key=${apiKey}`).then(response =&gt; {
    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(&quot;songs&quot;) ? JSON.parse(localStorage.getItem(&quot;songs&quot;)) : [];
    songs.push(userData);

    // Only saving to localStorage if it doesn&#39;t exist
    if (!isSongSaved(userData.songName)) { 
      localStorage.setItem(&quot;songs&quot;, JSON.stringify(songs));
    }
    
    navigate(&quot;/&quot;);
});

答案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(&quot;songs&quot;) || &quot;[]&quot;)
const isAlreadySaved = songs.some(song =&gt; 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.

huangapple
  • 本文由 发表于 2023年3月21日 03:33:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75794552.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定