Local Storage: Put it in your pocket
Put it in your pocket, put it in your back pocket Oh OH oHh
For the uninitiated:
Taking a break from my other posts on how being a music teacher has changed how I learn code, I wanted to take a minute and talk about a helpful tool that I came across during my most recent Javascript project. Local Storage, or as I call it, your browsers pocket!
I encountered an issue connecting a few of my models. In this case, I had a User, who had many Likes, and Constellations, who also had many Likes. In order for me to create an instance of a Like and have it append properly to a page, the Like class needed access to both the User and Constellation classes. I knew I had access to the Constellation Class, but couldn’t figure out how to implement the user class which was being created in another section of code. Enter local storage:
Local Storage allows you to access a stored object in the documents origin. Whatever you save to local storage is then held in the browser until it’s manually deleted. This is similar to Session Storage, but session storage will empty itself when the page session ends. Think of it as a surgical tech holding a scalpel for a head surgeon, or a video game character stuffing their bags with random trinkets that they’ll probably hold onto until the end of the game. Local Storage gives you a way to access things that you wouldn’t normally be able to. The best part is, it’s built right into your browser!
Let’s take a look at the code I mentioned earlier. On line 113, I’m using localStorage to set the value of username to localStorage. That variable is then put into a key value pair to be called in my fetch. As of right now, localStorage will contain my username, but I also need the id to create an instance of a Like. Line 127 covers that by taking my JSON data and setting the user id to the username that local storage currently has. We now have access to both my username and it’s id!
Now that we have access to the username and it’s id, we can implement it into our likes.
When we use localStorage you need to remember that even though it’s giving you access to something, you still need to call it by it’s name and not the content that’s saved to it. That should be easy because in the case of the code above, I needed to match the user_id foreign key with the id saved in local storage. Now we have both foreign keys needed to create an instance of a Like!
P.S. — If you wanted to remove what’s inside local storage, it’s as easy as typing localStorage.clear();
in your browser console.