bigskysoftware / bigskysoftware/htmx
htmx.ajax requests promise fulfilled too early
- Dominant language
- JavaScript
- Stars
- 49.4k
- Forks
- 1.7k
- Avg merge
- 3d 22h
- Merged PRs (30d)
- 30
Description
When using htmx.ajax the returned promise is fulfilled before htmx finishes all DOM manipulations.
Here is an example. One would think that the displayed box is blue after everything finished but it is red. Why? Because htmx copies some classes from the old elements to the new ones after the ajax promise is fulfilled.
1. html is loaded and the box is gray
2. js gets executed and the ajax call is made
3. the ajax promise is fulfilled and the color is switched to blue
4. htmx calls some settle methods and overwrites the changes made in step 3.
5. the box has the wrong color
`index.html`
```html
Basic example
window.htmx.ajax("GET", "./main.html", {
source: "#main",
target: "#main",
swap: "innerHTML",
}).then(() => {
console.log("promise resolved");
document.getElementById("box").classList.remove("bg-red-200");
document.getElementById("box").classList.add("bg-blue-200")
});
```
`main.html`
```html
```
My current workaround is using `htmx:afterSettle`, but this is inconvenient, because the data flow is now broken and we need to associate the data with the corresponding settle event.
```js
var boxState;
document.addEventListener("htmx:afterSettle, (e) => {
if (e.detail.pathInfo.requestPath === "./main.html") {
// do stuff with boxState
}
});
// somewhere else
boxState = state;
window.htmx.ajax("GET", "./main.html", {
source: "#main",
target: "#main",
swap: "innerHTML",
});
```
Here the log with `htmx.logAll()`:
```diff
htmx.esm.js:895 htmx:confirm
htmx.esm.js:895 htmx:configRequest
htmx.esm.js:895 htmx:validateUrl
htmx.esm.js:895 htmx:beforeRequest
htmx.esm.js:895 htmx:beforeSend
htmx.esm.js:895 htmx:xhr:loadstart
htmx.esm.js:895 htmx:beforeProcessNode …
htmx.esm.js:895 htmx:load … {elt: body.h-full.w-full.m-0}
htmx.esm.js:895 htmx:xhr:progress
htmx.esm.js:895 htmx:beforeOnLoad
htmx.esm.js:895 htmx:beforeSwap
htmx.esm.js:895 htmx:beforeCleanupElement
htmx.esm.js:895 htmx:beforeCleanupElement " " {elt: text}
htmx.esm.js:895 htmx:beforeCleanupElement " " {elt: text}
htmx.esm.js:895 htmx:afterSwap
htmx.esm.js:895 htmx:afterRequest
htmx.esm.js:895 htmx:afterOnLoad
- renderer.ts:19 promise resolved
htmx.esm.js:895 htmx:xhr:loadend
htmx.esm.js:895 htmx:beforeProcessNode {elt: script}
htmx.esm.js:895 htmx:load {elt: script}
htmx.esm.js:895 htmx:beforeProcessNode
htmx.esm.js:895 htmx:load
htmx.esm.js:895 htmx:afterSettle
```
Contributor guide
Assessment
This issue has not been assessed yet.