Persisting data on the client with Alpine.js
Content Index
Next, I want to show you how you can persist your data (in this case, a whole file) in the browser's local storage.
There are countless ways to do this, and we already have all the tools we've covered in previous posts, from the basics to using x-ref in Alpine to reference HTML elements, especially when using native JavaScript. But, since we're using Alpine.js in this case, we can take advantage of a plugin specifically designed for this purpose.
https://www.npmjs.com/package/@alpinejs/persist
We import the plugin through the CDN or Node, which is important as indicated here; you have to include it, curiously, before the alpine color:
import Alpine from 'alpinejs'
import persist from '@alpinejs/persist'
Alpine.plugin(persist)Or via the CDN which will be our case:
<script defer src="https://unpkg.com/@alpinejs/persist@3.x.x/dist/cdn.min.js"></script>We're using the CDN; you can download it and copy it into your project, or you can reference it directly from the URL.
Experiment
Let's run a quick test.
Let's define a count variable using the plugin:
count: Alpine.$persist(10),If we don't see any errors, open your browser's developer tools, go to the Application > Local Storage tab, and our count variable should appear there with the value 10, which is what we initially set.
Other values, such as PayPal, may also appear, but they're not relevant. What we're interested in is the one we set.
It's that easy.
Testing persistence
From there, we can modify count throughout our application, and absolutely nothing will happen: it will remain persistent.
For example, if we now enter:
count: Alpine.$persist(2)And we look at the local storage again, we will see the updated value.
Persisting arrays: a list of all
Now we're going to persist an array, like a list of tasks (todos).
The process is the same.
I'm going to duplicate the previous code and comment it out for your reference.
We'll use the plugin again:
todos: Alpine.$persist([])Remember that the $ symbol indicates that it's an internal variable, in this case, belonging to the plugin.
- We define the initialization value as an empty array.
- We return to the browser, and if there isn't a todo, we can create one.
Now, if we reload the page, we'll see that the todo we created earlier is still there.
The next step is to learn how to create sortable lists using drag and drop in Alpine.
I agree to receive announcements of interest about this Blog.
We will learn how to use the Alpine persist plugin with which we can persist data on the client.