Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

221
Visualizações
How to integrate AlpineJS Persist onto a toggle using localStoage

I have the following built with TailwindCSS and AplineJS. When the toggle is switched is saves the localStorage correctly. But when the page is refreshed the local storage sticks and is correct but the toggle goes to the default stage.

I asked over on the Github help page and they kindly stated that I need to use AlpineJS Persist... https://alpinejs.dev/plugins/persist

This is their reply.

You might want to just consider using Persist plugin https://alpinejs.dev/plugins/persist. You can see the example handles this case and if you want to use localStorage directly you can just set it on x-init.

In the x-init you'd just get the value from local storage and set it if so

Well, I'm at a loss on how to put this together, I'm new to development and even newer with Alpine. I'd be very grateful if someone can point me in the right direction.

Many thanks.

https://codepen.io/williamharvey/pen/xxXaJgM

    <div 
    class="flex w-full items-center bg-gray-100 border-b border-gray-200 px-5 py-3 text-sm"
    x-data="{ cookieConsent1: localStorage.getItem('cookieConsent1') === 'true'} "
    x-init="$watch('!cookieConsent1', val => localStorage.setItem('cookieConsent1', val))">
      <div class="flex-1">
        <p>Cookies that remember your settings</p>
      </div>
      <div class="w-10 text-right">
        <button type="button" 
            class="relative inline-flex flex-shrink-0 h-6 w-11 border-2 border-transparent rounded-full cursor-pointer transition-colors ease-in-out duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-300 bg-gray-200" 
            x-data="{ on: true }" 
            @click="on = !on;cookieConsent1 = !cookieConsent1"
            x-state:on="Not Enabled" 
            x-state:off="Enabled" 
            :class="{ 'bg-green-400': on, 'bg-gray-200': !(on) }">
              <span class="pointer-events-none inline-block h-5 w-5 rounded-full bg-white shadow transform ring-0 transition ease-in-out duration-200 translate-x-0" x-state:on="Enabled" x-state:off="Not Enabled" :class="{ 'translate-x-5': on, 'translate-x-0': !(on) }"></span>
        </button>
      </div>
    </div>
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The Persist plugin is a thin wrapper around localStorage, I recommend to read its source code, it's only a few lines of code and easy to understand what is happening.

I modified your example to use the plugin:

<div class="flex w-full items-center bg-gray-100 border-b border-gray-200 px-5 py-3 text-sm"
  x-data="{ cookieConsent1: $persist(false) }">
  <div class="flex-1">
    <p>Cookies that remember your settings</p>
  </div>
  <div class="w-10 text-right">
    <button type="button"
            class="relative inline-flex flex-shrink-0 h-6 w-11 border-2 border-transparent rounded-full cursor-pointer transition-colors ease-in-out duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-300 bg-gray-200"
            @click="cookieConsent1 = !cookieConsent1" 
            :class="cookieConsent1 ? 'bg-green-400' : 'bg-gray-200'">
      <span class="pointer-events-none inline-block h-5 w-5 rounded-full bg-white shadow transform ring-0 transition ease-in-out duration-200 translate-x-0"
            :class="cookieConsent1 ? 'translate-x-5' : 'translate-x-0'"></span>
    </button>
  </div>
</div>

Let's see how does it work. The key point is the cookieConsent1: $persist(false) in the x-data attribute. On the first occasion it makes AlpineJS to create a "normal" variable named cookieConsent1 and simultaneously a variable named _x_cookieConsent1 in the local storage (the _x_ is the default prefix to avoid name collision). Initially it will use the provided default value: false.

The persist plugin also creates a watcher for cookieConsent1 variable, that updates the value of the variable inside the local storage every time cookieConsent1 changes.

Let's say we click the button once, so the variable becomes true. The persist module updates the value in the local storage, so now it is also true. If we refresh the page, AlpineJS and persist module will detect that we have a _x_cookieConsent1 variable in our local storage that corresponds to the cookieConsent1 AlpineJS variable, therefore it will initialize the cookieConsent1 with the value stored in the local storage instead the default false.

If you open your browser's development console and go to the Application (or Storage) tab and select the localStorage from the list, you can see the _x_cookieConsent1 variable changes every time you click on the button.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda