Automatic update of displayed data from localStorage using AlpineJS

Viewed 56

I'm trying to use AlpineJS to update the displayed data from localStorage every time I click a button.

I have two buttons that use setItem to update the value in localStorage.

This all works, but I can't figure out how to use AlpineJS to update the displayed data (using getItem) when the button is clicked.

When the button is clicked, the value in localStorage does change, but I have to reload the page to update the data on FE.

Could someone give me some advice on how to solve this using AlpineJS?

CodePen

CodePen link

I'm new to AlpineJS and I've tried the documentation, but I really don't know how to grasp it.

Thank you in advance for any tips

1 Answers

Your approach is not working because localStorage is not reactive, so you need a page reload to see the mutated state. Everything you do on the frontend should utilize reactive Alpine.js variables and use a watcher to sync the state of these variables with the localStorage. Furthermore Alpine.js provides a localStorage plugin, so you don't even have to sync them manually just put a $persist() to the respective variables:

<!-- Alpine Plugins -->
<script defer src="https://unpkg.com/@alpinejs/persist@3.x.x/dist/cdn.min.js"></script>
 
<!-- Alpine Core -->
<script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>

<div x-data="{ name: $persist('') }">
  <button @click="name = 'Link'">Set name to Link</button>
  <button @click="name = 'Zelda'">Set name to Zelda</button>
  <div x-text='`Selected name: ${name}`'></div>
</div>
Related