-
My interpretation of the documentation for htmx:configRequest is that event handlers should run to completion before the ajax call is initiated. Without this expectation, request parameters cannot be expected to be updated before the ajax request is sent (unless by chance the handler completes first). I am not, however, observing this behavior. It occurs to me that events run asynchronously so maybe my expectations here are flawed. If so, how can I modify request parameters before issuing the ajax request? My scenario requires me to fetch a token (via JS fetch) from a third-party api and include that token in the request to my own endpoint. That intermediate request takes time. If I debug into my frontend JS token-retrieval code, I see my page reload with errors after ajax submission while I have an open breakpoint in the event handler for htmx:configRequest. Is this expected behavior? Is there an alternative approach? I believe that other events such as htmx:beforeRequest would be subject to the same behavior. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hey, events do not run asynchronously. What is probably asynchronous in your scenario though, is that separate request you're making to get a token. I guess that what you could do here is, simply don't use <button id="button">Click me</button>
<script type="text/javascript">
function timeout(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
document.getElementById("button").addEventListener("click", async function(evt) {
// You would retrieve your token here
await timeout(3000);
htmx.ajax("POST", "/test", {
values: {
token: "token_value",
},
target: "#button",
swap: "innerHTML",
})
})
</script> Depending on your situation, you could also retrieve your token ahead of time so that it's already in memory when the htmx requests is fired, which would allow you to stick to htmx:configRequest |
Beta Was this translation helpful? Give feedback.
Hey, events do not run asynchronously.
You can observe that in this JSFiddle, where the htmx:configRequest handler waits for 3 seconds before releasing. The request isn't sent before that handler exits.
What is probably asynchronous in your scenario though, is that separate request you're making to get a token.
htmx doesn't support async listeners, so something like this JSFiddle won't work, and the request will be sent, ignoring the
await
I guess that what you could do here is, simply don't use
htmx:configRequest
, rather bind your own JS listener that fetches the token then calls htmx.ajax to make the htmx requestSomething like this, that you can play it on this JSFiddle