terenceponce

terenceponce

How to use Phoenix 1.7 Streams on LiveComponent preload?

The recent Phoenix 1.7 came with Streams. The example given in the blog post was straightforward and easy to understand.

However, how would you use them when preloading a LiveComponent?

Given the example about preloading from the docs:

def preload(list_of_assigns) do
  list_of_ids = Enum.map(list_of_assigns, & &1.id)

  users =
    from(u in User, where: u.id in ^list_of_ids, select: {u.id, u})
    |> Repo.all()
    |> Map.new()

  Enum.map(list_of_assigns, fn assigns ->
    Map.put(assigns, :user, users[assigns.id])
  end)
end

Would it be possible to do it in the Map.put() section? Is it even possible to do streams when preloading?

Marked As Solved

codeanpeace

codeanpeace

This preloading example from the docs demonstrates how to avoid an n+1 query, which the stream example from the blog posts accomplishes by calling Blog.list_posts() that likely looks something like def list_posts(), do: Repo.all(MyApp.Post).

So in this case, preloading database resources into socket assigns may well be unnecessary/superfluous since these resources have already been added into the socket streams. And since one of the big advantages of streams is to offload storing of collections in memory on the server, I would think twice about about preloading and storing these same collections in memory on the server via socket assigns when using streams.

I haven’t tested it, but this could be one way of passing streams into multiple LiveComponents via assigns.

defmodule DemoWeb.PostLive.Index do
  use DemoWeb, :live_view

  alias Demo.Blog
  alias Demo.Blog.Post

  @impl true
  def mount(_params, _session, socket) do
    {:ok, stream(socket, :posts, Blog.list_posts())}
  end

  ...
end
# index.html.heex
<%= for post <- @streams.posts do %>
  <.live_component module={PostComponent} id={post.id} post={post} />
<% end %>

On another note, the following section of the Phoenix.LiveComponent docs on Preloading and update might help in understanding what @josevalim is saying.

So on first render, the following callbacks will be invoked:

preload(list_of_assigns) -> mount(socket) -> update(assigns, socket) -> render(assigns)

On subsequent renders, these callbacks will be invoked:

preload(list_of_assigns) -> update(assigns, socket) -> render(assigns)

Since you need the socket to pass into the stream, stream_insert, or stream_delete functions, only the mount and update LiveComponent callbacks can interact with streams.

Also Liked

josevalim

josevalim

Creator of Elixir

The main point is that preload does not know about streams. All the data in preload is copied to the socket in the update/2 callback. So that would be the place to insert data into the stream. If you give it a try, I can gladly review and provide pointers.

josevalim

josevalim

Creator of Elixir

The preload happens outside of the LiveComponent. You don’t really have access to the socket there. So for streams in live components, you can define it on mount, prepare the assigns on preload, and then load them into the stream on update.

josevalim

josevalim

Creator of Elixir

I just gave some pointers, @codeanpeace gave the proper and complete answer. :slight_smile:

Where Next?

Popular in Questions Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
nobody
How to bind a phoenix app to a specific ip address? could not find anything about that, nowhere, unfortunately, but for me this is quite...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lists...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
Lily
In templates/appointment/index.html.eex: &lt;%= for appointment &lt;- @appointments do %&gt; &lt;tr&gt; &lt;td&gt;&lt;%= appoi...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
earth10
Hi, I’m just starting to build a side-project with Elixir and Phoenix and doing some basic test with Elixir alone. What strikes me is th...
New

Other popular topics Top

Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
Qqwy
Update: How to use the Blogs &amp; Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3271 127089 1222
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement