skip to Main Content

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


  1. 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("/");
    });
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search