I'm trying to build a live stock view with Phoenix LiveView. I get the new data and it also gets updated in my Database. The problem is that when there are e.g. 10 stocks and one gets updated only the updated one is shown. Here are the relevant code snippets. I'm using the PubSub System for sending/receiving events.
@impl true
def mount(_params, _session, socket) do
if connected?(socket), do: Stockview.subscribe()
{:ok, assign(socket, :stocks, Stockview.list_stocks()), temporary_assigns: [stocks: []]}
end
@impl true
def handle_info({:stock_updated, stock}, socket) do
{:noreply, update(socket, :stocks, fn stocks ->
[stock | stocks]
end)}
end
When inspecting the "stocks" list it is empty.
The object "stock" looks like this:
%EzStocks.Stockview.Stock{
__meta__: #Ecto.Schema.Metadata<:loaded, "stocks">,
ask_price: 178.38,
id: 26,
inserted_at: ~N[2020-10-08 01:26:20],
isin: "US5949181045",
name: "MICROSOFT CORP",
sell_price: 178.2,
updated_at: ~N[2020-10-08 10:52:18]
}
My template for rendering:
<h1>Listing Stocks</h1>
<%= if @live_action in [:new, :edit] do %>
<%= live_modal @socket, EzStocksWeb.StockLive.FormComponent,
id: @stock.id || :new,
title: @page_title,
action: @live_action,
stock: @stock,
return_to: Routes.stock_index_path(@socket, :index) %>
<% end %>
<table>
<thead>
<tr>
<th>Name</th>
<th>ISIN / WKN</th>
<th>Ask price</th>
<th>Sell price</th>
<th></th>
</tr>
</thead>
<div id="st">
<tbody id="stocks">
<div id="stocks" phx-update="prepend">
<%= for stock <- @stocks do %>
<p id="<%= stock.id %>">
<tr id="stock-<%= stock.id %>">
<td><%= live_redirect stock.name, to: Routes.stock_show_path(@socket, :show, stock) %></td>
<td><%= stock.isin %></td>
<td><%= stock.ask_price %></td>
<td><%= stock.sell_price %></td>
</p>
<td>
<span><%= link "Delete", to: "#", phx_click: "delete", phx_value_id: stock.id %></span>
</td>
</tr>
<% end %>
</div>
</tbody>
</div>
</table>
<span><%= live_patch "New Stock", to: Routes.stock_index_path(@socket, :new) %></span>
I'd like to update the data and see the complete list, not just the updated object.
Thank you!