Flash message to disappear after 5 seconds?

But How Do We Generalize This?

I haven’t wired this up for all the other places CRUD activities take place (like User Settings, for example). This solution will require repeating this logic in all the places put_flash is invoked. To say the most, that is very not DRY.

To keep it dry, maybe have a look at attach_hook/4 in conjunction with on_mount?

To give an example, I have something like this:

  def on_mount(:subscribe_to_runs, _params, _session, socket) do
     # ... 

    socket =
      socket
      |> attach_hook(
        :hide_flash,
        :handle_info,
        &hide_flash/2
      )

    {:cont, socket}
  end

  defp hide_flash(:hide_flash, socket) do
    {:halt, clear_flash(socket)}
  end

And this is mounted to live_session in router.ex

    live_session :app,
      on_mount: [
        {HanekawaWeb.SubscribeToRunsHook, :subscribe_to_runs}
      ] do
      live "/pipelines", PipelineListLiveView
      live "/pipelines/:id", PipelineLiveView
      live "/runs", RunListLiveView
       # ...
    end

Now the logic to hide the flash is in one place.

I do agree that more could be done for flash though!

4 Likes