Automatically clearing flash messages in Phoenix LiveView

Hey, I created a hook to automatically clear flash messages after 5 seconds, in case it’s of anyone’s interest :slight_smile:

Here’s the code

// app.js
let liveSocket = new LiveSocket("/live", Socket, {
  // ...
  hooks: {
    AutoClearFlash: {
      mounted() {
        let ignoredIDs = ["client-error", "server-error"];
        if (ignoredIDs.includes(this.el.id)) return;

        let hideElementAfter = 5000; // ms
        let clearFlashAfter = hideElementAfter + 500; // ms

        // first hide the element
        setTimeout(() => {
          this.el.style.opacity = 0;
        }, hideElementAfter);

        // then clear the flash
        setTimeout(() => {
          this.pushEvent("lv:clear-flash");
        }, clearFlashAfter);
      },
    },
  },
});

I also created a post on dev.to with more details: Automatically clearing flash messages in Phoenix LiveView - DEV Community

7 Likes