What's the difference between the "root_view" and "view" in a Socket?

I’ve been messing around with LiveView for about a week now and before I say anything else let me just state… I love this! Basically, thank you to everyone who has built this.

I just started turning some early experiments into components yesterday and was trying to figure out how to have a component get the route from the parent view. I figured the parent view had to be included in the component socket and sure enough, I found it… twice.

Sockets have both root_view and view attributes. This leads me to two questions:

  1. What’s the difference? In the simple cases I’ve been working on the module is always the same but I cannot imagine that’s always going to be the case.
  2. More generally, I figured I would just check the source on the Socket and it’d give me an answer. It didn’t. Does someone (and it could be me!) just need to contribute documentation for what all these attributes or am I looking in the wrong place?

It is used when you have nested live views and they are rendered in the same LiveView process … the root_view is the top-most-parent’s view, and the view is the nested LiveView’s own local view. This is triggered when you call live_render(@socket, ..) in your leex template.

The preferred method these days is to use live_components, which you are already using, which accomplishes the same thing (1 process only) but it doesn’t have this view oddness.

That said, this is all implementation detail stuff (which is why it isn’t documented more, I imagine) and really should be needed to be touched.

When you say you are trying to get the “route” from the parent view … do you mean you are looking for what the parent is so you can pass it to Routes to build a path or url? or? (asking because depending on what you want to do, there may be better ways…)

That’s exactly what I am trying to do. The component needs to build a path with query string. So it needs to reference itself in a sense since the component can be used in multiple places.

Admittedly components + query strings is a bit awkward since a component does not touch handle_params on its own.

(My inexperience might be the main issue here.)

A typical approach is to hand the necessary data in with assigns. The optional 3rd argument to live_component are assigns, including possibly an id for stateful components.

This is particularly nice as it moves implementation assumptions such as “this information is in the query string” to the top-level LiveView, and the components do not have to care where that data comes from or how it is managed.

It also makes it explicit what data that component needs, which I’ve found helps with both reusability (fewer assumptions in the component == looser coupling) and maintainability (did that param move out of the query string? no problem!) later on