HTMX + AlpineJS: back button issues (broken re-initialisation of Alpine components) #2931
Unanswered
anentropic
asked this question in
Q&A
Replies: 1 comment 1 reply
-
Actually But you have to clear the browser cache/go incognito and not just reload the page, otherwise it carries on with old behaviour and the history ordering gets totally messed up if you just toggle the setting and try to continue I guess disabling HTMX history gives behaviour much more like the browser native one And presumably we can still benefit from browser cache of the server response if http headers are configured correctly |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I'm using HTMX so that I can get loading spinner when navigating to a new page. The combination of HTMX+Alpine seems popular, and I have used Alpine to wrap some 3rd party libs (Apache ECharts...) into Alpine components that can be configured from HTML
x-data
attr and initialise themselves when added to the DOM.Things work great when clicking forwards, but when using the browser back button I get some issues.
It's mostly where the component initialisation has added content to the DOM. When clicking back it seems that the full state of the HTML is restored, then the Alpine component init runs again. So I get like duplicate EChart content in the parent alpine div.
If I remove HTMX then this symptom doesn't occur, so there seems to be something different about how things behave via the HTMX swap. (I tried with
hx-history="false"
but symptoms still occur).I can see in the no-HTMX case that Alpine init still occurs when clicking back, so the difference is presumably in the state of the HTML that is being restored.
My gut feel is that the browser is restoring the 'raw' state of the HTML as it was first downloaded then re-running the JS inits on top. Whereas HTMX stores the current state of the page, at the time you click back or forwards, into local storage then restores that, then the Alpine inits run because new node was added to DOM.
I tried using the alpine-morph plugin but it didn't fix the issue (and it caused a new layout issue when clicking forwards)
I can think of two possible ways forward:
alpine:init
event and snapshot the page state before Alpine initialises on first page load, and somehow force HTMX to save/restore that state instead of snapping a new one when you click backIt feels weird that I would be the first person to run into these issues when HTMX+Alpine seems like a popular combo?
Is there a simpler way around this?
Anyone encountered anything similar?
Beta Was this translation helpful? Give feedback.
All reactions