I cannot get toggle state to remember state on refresh, using alpinejs, tailwindcss & localStorage #2565
Unanswered
richwebmedia
asked this question in
1. Help
Replies: 1 comment 2 replies
-
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. |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
First of all I apologise if this is not the place to ask for some guidance. Please let me know if that's the case.
I have a toggle using TailwindCSS that when toggled sets a localStorage to true or false using AlpineJS. 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.
I'm new to development in general but I'm looking for an else if on the x-data="{ on: true }" but I don't think that's possible.
I know this example is wrong, but this is what I'm trying to achieve.
// x-data="{ localStorage.getItem('Consent3') === true: on: true, localStorage.getItem('Consent3') === false: on: false }"
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.
Cookies that measure website use
Beta Was this translation helpful? Give feedback.
All reactions