3 ms·
I started using this pattern in my LiveView projects, and finally rolled it into a common module for others to use. I've found it really helps clean up the mou
by gnutrino 3y ago
I started using this pattern in my LiveView projects, and finally rolled it into a common module for others to use. I've found it really helps clean up the mount function, which can get pretty messy as your LiveViews grow over time.
My apologies for the terrible elixir syntax highlighting in this post. I keep putting off finding a good way to do this on Blogger.
- conradfr 3y agoAre you sure your import should not be: import Phoenix.Socket, only: [assign: 2, assign: 3]
- gnutrino 3y agoI believe you are correct. I could probably remove the imports altogether, and just prefix those functions with `Phoenix.LiveView`.
- sodapopcan 3y ago+1 for removing imports! Not that importing is useless but single-use imports drive me a bit nuts. Even just using it a few times. It's nice to be able to jump to some code and know exactly where everything is coming from without having to jump around the file.
- barkerja 3y agoKnowing the origin of the function is a huge benefit, but also imports create compile time dependency. In this case, it's not an issue, but when you're importing a lot of things across your codebase, it can become an issue.
- sodapopcan 3y agoYa, if you design relationships as a DAG then those sorts of compile time dependencies don't matter. Of course sometimes it can't be avoided (Phoenix router, ecto relationships) the router isn't updated very often and schemas don't have too far a reach (at least they don't if you keep them in their contexts). I don't avoid import but I generally I strive to import one module where I'm going to be using many functions. I rarely bother with `only` unless it's absolutely necessary due to conflicts otherwise specifying `only` is a good indication I don't even need to import.
- nivertech 3y agoI'll take compile-time dependency over unchecked run-time dependency (almost) every time!
- sodapopcan 3y agoWhen using LiveView I always use: import Phoenix.Component, only: [assign: 2, assign: 3] https://hexdocs.pm/phoenix_live_view/Phoenix.Component.html#assign/2 https://hexdocs.pm/phoenix_live_view/Phoenix.Component.html#... Importing from Socket should work, but you're right, the code in the post wouldn't work. They use to be in LiveView but got moved to Component.
- gnutrino 3y agoI'm still on 17.X, so that probably explains the discrepancy here. I think I tried doing a major version bump a while back and things didn't compile so I put it on the backlog and forgot about it. It may be time to revisit before I get too far behind.