LiveView architecture decisions: LiveViews vs LiveComponents and where and how to store data?

I’m working on a social network with posts and comments using LiveView, and I’m trying to figure out how and when to use the different constructs LiveView provides. There are a few different pages where you will see lists of posts: a main feed with friends’ posts, a user profile page with that user’s posts, and on the show page for a single post. Posts behave similarly in all these cases (i.e. they can be viewed and edited on all three and on the feed and user profile pages new posts can be created).

Here’s a diagram of the rough relationships of the different parts I’m trying to organize:

To me, it seems logical for each blue box that isn’t the top-level LiveView to be its own LiveComponent because all of them will be used in more than one place, but this presents some questions:

How does the comments stream get updated after the new comment form is submitted?

My impression is that there is no direct way to communicate from a child to a parent when the parent isn’t the top-level LiveView, so I would have to send an event from the new comment form to the top-level LiveView and then call send_update to get it to the post component. That seems a bit convoluted, but I’m not sure there’s another way?

Also I’ve been hearing and reading about the choice between storing posts as a list of post ids and populating them in preload versus populating them in the top level parent and passing a whole post object to each Post component, and I’m not sure how to think about that decision either (or how that decision impacts if or where to use streams for posts and/or comments).

I could just handle everything in the top-level LiveView and avoid this issue altogether, but that would mean duplicating a fair amount of functionality between the top-level LiveViews for the post show page, the main feed page, and the user profile page.

And having thought through all of the above as well as I can, I’m just…not sure what I’m supposed to be doing here or how I’m supposed to be thinking about it. Any thoughts or advice are appreciated. How would you organize this? How would you use LiveComponents vs other constructs and what data would you put where?

1 Like

There are few things that could be changed:

posts/show.ex LiveViewposts/index.ex LiveView
postposts/show.ex LiveView
commentposts/:post_id/:comment_id as posts/comments/show.ex LiveView

posts → uses table function component
comments → uses table function component

comment and post forms should be LiveComponent

This way you have flat structure:

  1. One “top” LiveView (post index, post show or comment show)
  2. table function component uses attr for sending a specific message to the parent LiveView
  3. PostForm and CommentForm are LiveComponent just like in generators

Also you can take a look at Events section for targeting a specific parent.