I am following a tutorial, and trying to delete a record from database using liveview. All the examples that I saw on different resources on the internet about Phoenix LiveView use the following:
<span><%= link "Delete", to: "#", phx_click: "delete", phx_value_id: product.id, data: [confirm: "Are you sure?"] %></span>
@impl true
def handle_event("delete", %{"id" => id}, socket) do
product = Store.get_product!(id)
{:ok, _} = Store.delete_product(faq)
{:noreply, assign(socket, :products, list_products())}
end
defp list_products do
Store.list_products()
end
this will delete the record, but I will have to refresh every-time to update my index page.
why not use <%= live_patch %> like in an update event?
your answer help me to look up the difference. And I removed the product_component.ex and added inline html inside the index.html.heex instead, and it is working in fact. I was also mixing between LEEX and HEEX annotations, so that probably contributed to the issue.
added this to my index.html.heex and removed the product_component.ex file
<tbody id="products">
<%= for product <- @products do %>
<tr id={"product-#{product.id}"}>
<td><%= product.name %></td>
<%= if(@current_user.id == product.user.id) do %>
<td>
<span>
<%= live_patch("Edit",
to: Routes.product_index_path(@socket, :edit, product)
) %>
</span>
</td>
<td>
<span>
<%= link("Delete",
to: "#",
phx_click: "delete",
phx_value_id: product.id,
data: [confirm: "Are you sure?"]
) %>
</span>
</td>
<% end %>
<td>
<%= live_redirect("Details",
to: Routes.product_show_path(@socket, :show, product)
) %>
</td>
</tr>
<% end %>
</tbody>
</table>