I have a toggle using TailwindCSS that when toggled sets a localStorage to true or false. This works, albeit it sets false when on. But my problem is that when the page refreshes the localStorage sticks but the toggle doesn’t and defaults the button to on.
Can anyone explain to me how I can achieve this? It would be greatly appreciated.
Here’s the codepen.
https://codepen.io/williamharvey/pen/xxXaJgM
And here’s the code.
<div
class="flex w-full items-center bg-gray-100 border-b border-gray-200 px-5 py-3 text-sm"
x-data="{cookieConsent3: localStorage.getItem('Consent3') === 'true'}"
x-init="$watch('cookieConsent3', val => localStorage.setItem('Consent3', val))"
x-bind:class="{ 'Consent3': cookieConsent3 }">
<div class="flex-1">
<p>Cookies that measure website use</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 }"
role="switch"
aria-checked="false"
:aria-checked="on.toString()"
@click="on = !on;cookieConsent3 = !cookieConsent3"
x-state:on="Enabled"
x-state:off="Not Enabled"
:class="{ 'bg-green-400': on, 'bg-gray-200': !(on) }">
<span class="sr-only">Use setting</span>
<span aria-hidden="true" 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>