[TRAIN WHISTLE]
Hello, and welcome to a supplemental p5.js tutorial.
In this tutorial, I'm going to show you
how to use localStorage.
Have you ever wanted your p5 sketch
to start up where it last left off?
Do you not feel like trying to figure out
some kind of complex cloud database storage solution?
Then you're in exactly the right place.
LocalStorage is for you.
If you're like me and you have a 90-day Wordle streak going,
[BUZZ] how does your phone or your computer
know that you've been playing it every day?
You didn't log in.
You didn't sign up for anything.
It just remembers you were there yesterday.
If you go to a different computer,
it doesn't know who you are.
This is all due to local storage.
Local storage means saving data locally in the browser itself--
your browser on your computer and there only.
It's not a robust database solution for user accounts
or high scores and multiplayer games,
or anything that really needs proper network communication
and data storage in the cloud.
But for just having a p5 sketch that runs and picks
some colors, and then the next time you run it,
those colors come back just for you working locally
on your own computer, it is just perfect.
So here I am in this tutorial with a very basic p5.js sketch.
It creates three sliders, each with a range between 0 and 255,
starting with the value of 0.
Then, in the draw loop, I pull the values from each slider
and use them to set the color values of the background.
Some red, a little bit of green.
Let's add a lot of blue.
Let's take out some of the green.
Let's add some more red.
And then we have-- mwah--
a beautiful pink.
What if I want, the next time I run this sketch,
to see that pink color again?
It's not going to happen just by rerunning the sketch.
Anytime you run a p5.js sketch, whether you're
loading it for the first time or rerunning it in the p5 Web
Editor, it starts fresh.
LocalStorage is something that comes as part of JavaScript
and the browser API.
It's part of the browser Window object.
And we could go through how to access, save, and retrieve data
from local storage in plain JavaScript.
But I'm here using p5.
And wouldn't you know it-- ah, mwah--
if you needed another reason to love p5,
it's got a set of helper wrapper functions
that allow you to put things in local storage
and retrieve them whenever it's convenient for you.
There are only two functions you need to know
in p5 to use local storage.
They're both found in the P5 Reference--
storeItem and getItem.
They do exactly like what they sound like they do.
StoreItem stores something in local storage, getItem
retrieves it from local storage.
First thing first, I need to figure out
when do I want to store the red, green, and blue values
in local storage.
I could put that in the draw loop, like, oh, I'm animating,
I'm animating, just store, store, store, store, store.
And that might be OK to do in some contexts.
But I think here I can basically choose
to save the values in local storage
anytime I've used the slider and the value has changed.
So here I've added the changed event,
which executes whenever I've completed
a change for the slider.
There is a different event called
input, which will continuously fire as I'm
moving the slider around.
But I think I can wait until I have completed
my motion of the slider.
Then, in the function, I'll call the p5 storeItem function.
StoreItem takes two arguments.
I need a key-- a unique string that names the piece of data
I want to save.
In this case, I'll call it "red."
So the key to unlock the data is "red."
And the data is just the value of the rSlider.
And let me just add a console.log
to make sure I see when this event is happening.
I'm going to move the red slider, let go,
and I see the 168 value.
And it should be stored in local storage now.
Then the question is, when do I want to load the data?
And I've kind of done this in a weird,
backwards way because I want to save the data while I'm
operating the sketch, but then I'm
thinking about the future, when I'm running it again, that I
want to retrieve the data.
So right there in setup, the moment I create the slider,
I should see if there is data available already stored.
Then I can set the slider to the color value
that I'm retrieving.
GetItem is the p5 local storage function to retrieve data.
I'm very sorry to overcomplicate this video,
but there's this new thing that's
happening in the p5 Web Editor.
When I type the word "red" as a string,
it'll actually create this automatic color picker,
which is kind of amazing.
And it would allow me to do so many wonderful things.
But it's getting in my way right now.
So I'm going to change the name of my key to "redValue."
So now I'm retrieving the red value.
If it doesn't exist, it will just
give me the value null back.
So as long as r is not equal to null, then
I can set the value of that slider to whatever I
retrieved from local storage.
I'm going to click Auto-refresh, which
could add some wonkiness if it's running and rerunning here.
I'm going to run the sketch.
I'm going to give myself a little bit of red.
I'm going to hit Stop.
And I'm going to run it again.
[TA-DA SOUND PLAYING]
Oh, local storage, where have you been all my life?
All the data is locally stored so it's not going anywhere.
It's just right there in your browser, and it works.
Oh, I love it.
Let's add the same thing for green and blue.
Let's see what we've got here.
First, we create three sliders.
Then we attempt to retrieve three
values from local storage--
a redValue, a greenValue, and a blueValue.
If there's a red value, set the red slider.
If there's a green value, set the green slider.
OK, this one I forgot to update.
If there's a blue value, set the blue slider.
And then make sure that any time I
change any of those slider values,
I store those three items.
Now, technically, if I'm only changing the red slider,
do I need to store the new green or blue?
But it's easier just for me to not worry about it
and always store all three anytime there's
a change to any of them.
Whoops.
I have a little typo here.
That needs to be a lowercase.
Everything is case-sensitive.
And now let's run this again.
Well, we start with that red value.
Now let me add a little green, add a little blue,
take the green down, get rid of all the red, more green,
and stop.
OK, everybody.
It's the moment of truth.
Let's run the sketch again.
[DING]
I love it!
One of the things that's really quite
wonderful about local storage is it saves the data
beyond any given session, meaning
if I were to quit the browser--
I'm going to do that right now--
then relaunch the browser, go to the p5 Web Editor,
log in, go back to my sketch and run it, I still have my data!
Oh, it's amazing!
Now if I were to open up a different browser,
go to an incognito window, maybe open up this page on my phone,
I wouldn't get these colors.
It doesn't even matter if I'm logged into the p5 Web Editor.
I'm going to log out, go to that sketch.
And it's still pulling that.
It has nothing to do with any account or anything anywhere.
It's just data that's being stored in the browser itself
that's running on this laptop.
Now, it's really up to the browser
to choose how it implements local storage.
So it depends what browser you're actually using.
But in almost all cases, I would imagine if you clear the cache
or clear your browsing history that local storage will also
be cleared.
If you want to dive a little deeper and look at the data
itself, you can look at your browser's developer tools.
Here in Chrome, I want to go to Application and then right here
under Storage, Local Storage.
Now I can see the key and value for all the data
that I'm storing.
Now, there's lots of extra stuff there.
One, the p5 Web Editor makes use of local storage.
Two, I've been playing around with this earlier
today so there's extra stuff in local storage.
It is unique to the domain.
So I can only have one redValue, greenValue,
or blueValue for this p5.js preview window, which
is what I'm actually seeing in the pane when the sketch runs.
So, amazingly, if I were to create a new sketch and call
getItem redValue, I'd still have that value.
So if I'm using local storage across multiple sketches
and always staying in the p5 Web Editor,
I've got to be careful about my naming.
Now, to keep things simple, I stored redValue, greenValue,
and blueValue all as separate items.
But one of the nice things about what p5 does
is it allows you to pass a JavaScript object.
And it will turn that into a string that
can be saved in local storage and then unpack it back
for you as a JavaScript object.
So I don't know how you found this video,
and JavaScript objects might be new to you.
I'll refer you to my tutorials about classes and objects
and those types of things.
But if that's familiar to you, let
me show you how that works with this example.
So, for me, what I'd want to do is create a new object.
I'm going to call it "colors" and give it three properties.
And then, instead of storing individual numbers,
I can store that full object associated with a single key.
I'll just name the key "colors" and save the colors.
This will also allow me to simplify these if statements
because I don't need to check each of them individually.
So now I'm asking for a JavaScript
object called colors.
If it is not null, I can pull out the r, g, and b properties
and assign it to the correct slider.
Let's run the sketch again.
[BUZZ]
Uh-oh.
Unexpected end of input.
Oh, I just forgot an extra curly bracket here.
So I don't have my data from before
because I renamed everything.
But I can make this nice purple color, hit Stop, run it again.
And there we go.
Thank you to atomfighter and others in the Twitch chat
that are following along as I record this tutorial.
There's this excellent post on web.dev/storage-for-the-web
about different kinds of storage mechanisms-- session storage,
cookies, the file system API.
And I would encourage you to investigate those.
This is also where you will find some of the downsides of using
local storage.
And in fact, it even says it should
be avoided because it is synchronous,
blocks the main thread, is limited
to only 5 megabytes of data.
But these are actually the reasons
why I love local storage, because it's
a really quick and really easy solution for having persistence
without worrying about all sorts of asynchronous extra code
and data.
So if you just want proof of concept ability
to store some simple numbers, some simple data, some settings
for your creative coding application,
then I can't recommend it enough.
I could keep going with this example.
What if I used that color and drew in the canvas?
And then, every time you reloaded the page,
you got elements of your drawing back?
What if it were to tell you how many days in a row you drew?
All of these things are possible.
I would love to hear from you in the comments what
is your scenario that you might like to use local storage with.
I'll include extra examples linked
from the video description that will go along with this video.
And if there's anything that I really missed,
I could do a follow-up video and address it or come back to it
on a future live stream.
So thanks for watching.
I hope this little extra p5 video helped you with your day
and whatever you are coding.
And I'll see you next time on the Coding Train.
[MUSIC PLAYING]