Skip to content

Commit

Permalink
docs(blog): update htmx post (#6304)
Browse files Browse the repository at this point in the history
  • Loading branch information
necatiozmen authored Sep 6, 2024
1 parent 15a6bc0 commit 8983bbd
Showing 1 changed file with 146 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ image: https://refine.ams3.cdn.digitaloceanspaces.com/blog/2023-10-26-htmx/socia
hide_table_of_contents: false
---

**This article was last updated on August 21, 2024, to add sections on State Management with HTMX and Error Handling with HTMX.**

## Introduction

In this article, we will explore what HTMX is and its capabilities.
Expand Down Expand Up @@ -425,6 +427,51 @@ Events related to validation in HTMX are:

The code above is an illustration of an input using the htmx:validation. In the code, [hyperscript](https://hyperscript.org/) was used to validate the event to ensure that an input have the value `foo`.

## State Management Using HTMX

I'll just share some thoughts on how the whole state management thing works in HTMX, and how this might compare with how you've been doing it with traditional JavaScript frameworks like React and Vue.

### 1. **Server-Driven State**

HTMX is state management with a server-driven approach. It means most of the logic and state handling are done on the server rather than on the client. This contrasts sharply with JavaScript frameworks like React that handle state on the client side. Each and every action or interaction in HTMX (like form submissions and button clicks) creates a request that's made to a server. In response, it receives HTML back from the server to update the client-side DOM without any further effort on your part.

For example:

```html
<div hx-get="/get-data" hx-trigger="click" hx-swap="outerHTML">
Click to Get Data
</div>
```

Here, the state is maintained on the server, and HTMX will update the DOM according to the response from the server to keep the client in sync with the latest state.

### 2. **Client-Side State Management Not Possible**

Unlike React, where state is managed using `useState` and `useReducer`, HTMX relies on very little client-side state. Then, if you are in a server-centric world—which is quite good if your application is not one of these super-client interactive applications—the state management is easier, and you do not have to have all these huge, heavy client-side tools managing the state for you.

### 3. **Forms and Inputs Handling**

For forms, HTMX supports even form submission in an asynchronous fashion, whereby even the state of the form can be handled by directly listening on the server's responses. This eliminates all the boilerplate of tracking client-side state: the server is responsible for validation, processing, and changing state and then updating the UI accordingly.

Sample:

```html
<form hx-post="/submit-form" hx-swap="outerHTML">
<input name="username" type="text" />
<button type="submit">Submit</button>
</form>
```

In this case, the server is in control of the form submission, and it directly sends the server response back to the DOM, updating it accordingly.

### 4. **Persistence Across Requests**

Because HTMX is essentially server-driven, it can be used most productively with server-side session state or database-driven state that can be preserved across requests. This makes handling things like persistent user sessions, authentication, and long-running operations easy without the need to store state in the browser or client.

### 5. **Dealing with Complex State**

If your app needs more complex state management—like multiple interacting components or maintaining state across different elements...

## Animations with HTMX

HTMX is intended to allow you to add seamless animations and transitions to your web page using only CSS and HTML. You can now utilize the new [View Transitions API](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API) to create animations with HTMX.
Expand Down Expand Up @@ -558,6 +605,105 @@ htmx.logger = function (elt, event, data) {
};
```

## Error Handling in HTMX

I have a few thoughts about how error handling works in HTMX and how we could manage errors gracefully in our applications.

### 1. **Simple Error Handling**

HTMX has built-in events that can help us catch Ajax request errors or form submission errors in a custom manner. With an error like 404, 500, or a validation failure, we get an opportunity to intercept the error using the event `htmx:responseError`.

Here's how you would handle a trivial error event:

```javascript
document.body.addEventListener("htmx:responseError", function (evt) {
alert("An error occurred: " + evt.detail.xhr.status);
});
```

This event is triggered every time an AJAX request fails, and you can specify the response based on the HTTP status code, such as 404 or 500.

### 2. **Presenting Error Messages to Users**

Provide friendly UI error messages on page failure, rather than a pure alert or default browser error, by listening for the event `htmx:beforeSwap` and injecting error content into an area of the page you designate:

```javascript
document.body.addEventListener("htmx:beforeSwap", function (evt) {
if (evt.detail.xhr.status >= 400) {
evt.detail.shouldSwap = false;
document.getElementById("error-message").innerHTML =
"Something went wrong. Please try again.";
}
});
```
In this case, an error will prevent a default content swap and instead show the content of a custom error message in a `#error-message` div.
### 3. **Handling Form Validation Errors**
With HTMX, form validation is very easy to handle. For example, if the server returns an error about validation (e.g., 422 Unprocessable Entity), we can easily manage such a response and show validation messages without page reloading.
Here's an example:
```html
<form hx-post="/submit" hx-target="#form-errors" hx-swap="outerHTML">
<input name="username" type="text" />
<button type="submit">Submit</button>
</form>

<div id="form-errors"></div>
```
If the server returns validation errors, those can be added to the response and will be shown inside the `#form-errors` without a page reload.
### 4. **Graceful Fallback for Non-HTMX Browsers**
One thing HTMX is really good at is being able to progressively enhance your application, but you need to handle errors gracefully for your non-HTMX users—that is, those with JavaScript disabled. In that case, we return a full-page reload in case of necessity, so the classic form submission and error handling still work.
### 5. **Request-Specific Error Handling**
HTMX allows you to work with errors on a per-request basis by attaching the error handling logic to specific elements. For instance, if there is a button that triggers an AJAX request, you could listen for events like:
```javascript
document
.getElementById("my-button")
.addEventListener("htmx:responseError", function (evt) {
console.log("Error on this button request: " + evt.detail.xhr.status);
});
```
This allows granular error handling, where it is easy to distinguish the error responses for different parts of an application.
### 6. **Handling Different HTTP Error Codes**
HTMX does have some flexibility in how you can treat various HTTP error codes. For example, you might want to treat a `404` error differently from a `500` error or handle a `403` Forbidden by redirecting users to a login page:
```javascript
document.body.addEventListener("htmx:beforeSwap", function (evt) {
if (evt.detail.xhr.status === 404) {
alert("Page not found.");
evt.detail.shouldSwap = false;
} else if (evt.detail.xhr.status === 403) {
window.location.href = "/login";
}
});
```
For instance, we show an alert for `404` errors, and in case a `403` Forbidden error occurs, the user is redirected to the login page.
### 7. **Programmatically Aborting Requests**
Sometimes, you would want to programmatically cancel ongoing requests when a new one is triggered. HTMX provides the `htmx:abort` event for this:
```html
<button id="submit-btn" hx-post="/submit" hx-target="#result">Submit</button>
<button onclick="htmx.trigger('#submit-btn', 'htmx:abort')">
Cancel Request
</button>
```
This will cancel all requests made by the `Submit` button.
## Conclusion
In this article, we provided an overview of the HTMX library. we showed that you can achieve Ajax functionality without relying on JavaScript with HTMX, allowing you to construct dynamic applications at ease.
Expand Down

0 comments on commit 8983bbd

Please sign in to comment.