If you need to put a flash message in LiveView but want it to disappear after a few seconds, you might be surprised that LiveView does not have this built-in.

Here is how to do it:

All these changes go into your LiveView file.

In your mount function, assign an empty flash_timer.

assign(flash_timer: nil)

Define a :clear_flash handle info so we can send ourselves a message to clear the flash.

@impl true
def handle_info(:clear_flash, socket) do
  {:noreply, clear_flash(socket)}

Define a put_timed_flash function.

defp put_timed_flash(socket, key, message, timeout \\ 5000) do
  if socket.assigns.flash_timer do

  timer = Process.send_after(self(), :clear_flash, timeout)

  |> put_flash(key, message)
  |> assign(flash_timer: timer)

You’re done!

Now you can use it with the same interface as put_flash/3 but it also accepts an optional 4th timeout argument.

Example usage:

  "This message will disappear after the default of 5 seconds ⏳."

You can see it in action on quickaverage by clicking to copy the URL at the bottom or by clicking the “Clear Numbers” button.