LiveView and non-existent/optional values in assigns

As the app grows, so does its state. There are, however, things that are strictly optional, so dealing with them becomes either awkward, or unnecessary, or redundant.

This is bad, because “Generally speaking, avoid accessing variables inside LiveViews, as code that access variables is always executed on every render. This also applies to the assigns variable.” (see docs). That is, this code breaks change tracking.

<%= if assigns[:optional_data] != nil do %>
  Now we can access <%= @optional_data %>
<%end %>

A solution to this is to always set all data on mount to nil:

def mount(%{"id" => id}, _session, socket) do
 assign(
        socket,
        a_lot: ...,
        of_required: ,
        data: ...,
        already: ...,
        and_then: ...,
        optional_data: nil
      )
end

I personally don’t like this because there’s already a lot of data in the state, and adding more and more to it even if it’s optional… well, it sort of rubs me in the wrong way :smiley:

Is there a good way to do a @optional_data in a way that doesn’t break on non-existent data, doesn’t require breaking chaneg tracking or filling this data on mount? besides creating a custom compiler that deals with this? :slight_smile:

If assigns become to plenty my general next steps would be breaking functionality up into multiple pieces either at the functional level (helpers) or even at the structural level (split into components).

1 Like