Is there a way to create an after_mount callback for LiveView?

Is there a way to add a callback to AppWeb.live_view that will run after mount for every LiveView, similar to how on_mount runs before?

I have a really hacky workaround right now that starts a timer in on_mount to check the assigns after a delay.

I’m using Phoenix Live Favicon to set a dynamic Favicon on one of my liveviews (it uses push_event). When the user navigates away from that view, I need to reset the favicon to the default. I found this github issue about creating your own unmount function, but don’t think that would work because that’s after the view and socket are gone. I’m thinking the best way is then to add a callback that will check the assigns and update the favicon appropriately for every LiveView.


I would just send(self(), :check_favicon) from the mount callback if connected?(socket) is true.

Nice, that’s really elegant. It runs after handle_params which is where I actually need to be checking the assigns for the show/edit actions. I mistakenly thought after mount was the right spot.


1 Like

How about resetting the favicon in every view (Favicon.reset() in on_mount) and setting it only when needed in a view (mount or handle_params)?

The use case you have is very common I think so it would be nice to include the best solution in the docs.

That was my previous attempt: always reset in on_mount, sometimes set in mount (or handle_params). My issue with this was the reset and set were merged together and behaved inconsistently, usually resulting in the desired change not happening. I figured calling reset and set in a single load was just a bad practice on my part.

This seems to me a case of random order due to the merge of operations. I’ll look into it after the weekend, as explicit order has found a use case :slight_smile:

1 Like

Perfect, thanks! That would simplify the on_mount. Right now I have a large comment before my send(:check_favicon to prevent future me from breaking it during a refactor.

Live favicon could even provide optional on_mount reset callbacks if this feels like a common enough use case (view-specific favicons vs the more programatic ones). Happy to help out if this sounds worthwhile.

Turned out it was an unforseen use case indeed (and a bug on top of that).

A new version has been released and the post includes an example of the ‘on_mount’ reset method.

1 Like