How do you debug state changes using LiveViews?

I have found the source of the strange state issues.

In copy_web.ex I’d changed from the :app layout to the :root layout. If I change it back to :app, my problems disappear. I have not yet figured out why though.

def live_view do
    quote do
      use Phoenix.LiveView,
        layout: {CopyWeb.Layouts, :root}

      import PhoenixLiveReact

      unquote(html_helpers())
    end
  end
2 Likes

App and root layout are split because LV, or more specifically morphdom on the client, shouldn’t try to mess with any markup outside of <body>. And even more so you don’t want to apply the root layout twice, which might be the case here as well, unless you removed the application of the :root layout as a root_layout.

1 Like

Ok, good to know.

This is a major footgun. I lost two days because of this. And nearly ditched LiveView and Phoenix out of frustration, even though I’m really pleased with both LiveView and Phoenix otherwise!

There is documentation about it: Live layouts — Phoenix LiveView v1.0.7

Great!

But if you accidentally do what I did, change the layout to :root, it will take a long time to understand why your state behaves so strangely, at least for me.

I created a simple PR in the Phoenix repository. More intelligent people might have better solutions, but at least I’ve made an effort to contribute instead of just whining :slight_smile:

The behavior is indeed interesting. What’s going on is that the app.js is executed twice, because it is included twice in the initial render. That causes two LiveViews to be started that both try to control the same DOM and causing a lot of chaos. I’ll think about ways to make that fail in a more obvious way :smiley:

3 Likes

That explains a lot!

I saw two processes in LiveDebugger, which I thought was strange, but since it was the first time I used the tool, I thought one could be related to dev tools or something.

We should have some kind of warning in the future: complain loudly if LV is initialized twice by SteffenDE · Pull Request #3721 · phoenixframework/phoenix_live_view · GitHub

7 Likes

Love it! That’s a nice and clean solution. It would have saved me lots of time and energy!

1 Like