Does sending a message to 'self()' to update the state on mount have any downsides apart from not being able to use 'temporary_assigns'?

If I update my state in liveview like this:

def mount(_params, _session, socket) do
  send(self(), :fetch_initial_data)
  {:ok, assign(socket, data: [])}
end

def handle_info(:fetch_initial_data) do
  # Fetch some data from an API
  data = MyAPI.fetch_data()
  {:noreply, assign(socket, data: data)}
end

instead of the usual:

def mount(_params, _session, socket) do
  
  {:ok, assign(socket, data: MyAPI.fetch_data())}
end

apart from not being able to use temporary_assigns option in the mount as it will be useless, are there other downsides to this approach or bugs that can come up as a result of the approach?

:wave:

Is handle_info callback invoked during not connected mount? That is, is there any live view process to receive the message during the first time mount is invoked when connected?(socket) = false? If not, then the data is not fetched during the first time the liveview is rendered. It might be intended though, but then it’s usually achieved with connected?/1 helper instead of sending a message to self.

1 Like

I have tried it and handle_info is actually invoked twice once on the initial render and second when the liveview connection is established but I think it only sets the state of the socket when the liveview connection actually exists.

I believe the major downside of what you are doing is that if someone has js disabled the won’t see content. You might also be making expensive database queries that do nothing.

1 Like

It can also be a bit annoying in automated tests, since the first render won’t have the data.