Skip to content

Commit

Permalink
Fix updating item on show view
Browse files Browse the repository at this point in the history
  • Loading branch information
Flo0807 committed Feb 1, 2024
1 parent 9f84f07 commit d3dc342
Showing 1 changed file with 31 additions and 15 deletions.
46 changes: 31 additions & 15 deletions lib/backpex/live_resource.ex
Original file line number Diff line number Diff line change
Expand Up @@ -1364,28 +1364,27 @@ defmodule Backpex.LiveResource do
end

@impl Phoenix.LiveView
def handle_info({"backpex:" <> unquote(event_prefix) <> "deleted", item}, socket) do
if Enum.filter(socket.assigns.items, &(&1.id == item.id)) != [] do
{:noreply, refresh_items(socket)}
else
{:noreply, socket}
end
end

@impl Phoenix.LiveView
def handle_info({"backpex:" <> unquote(event_prefix) <> "created", item}, socket) do
def handle_info({"backpex:" <> unquote(event_prefix) <> "created", item}, socket)
when socket.assigns.live_action in [:index, :resource_action] do
{:noreply, refresh_items(socket)}
end

@impl Phoenix.LiveView
def handle_info({"backpex:" <> unquote(event_prefix) <> "updated", item}, socket) do
def handle_info({"backpex:" <> unquote(event_prefix) <> "deleted", item}, socket)
when socket.assigns.live_action in [:index, :resource_action] do
if Enum.filter(socket.assigns.items, &(&1.id == item.id)) != [] do
{:noreply, update_item(socket, item)}
{:noreply, refresh_items(socket)}
else
{:noreply, socket}
end
end

@impl Phoenix.LiveView
def handle_info({"backpex:" <> unquote(event_prefix) <> "updated", item}, socket)
when socket.assigns.live_action in [:index, :resource_action, :show] do
{:noreply, update_item(socket, item)}
end

@impl Phoenix.LiveView
def handle_info({:put_assoc, {key, value} = _assoc}, socket) do
changeset = Ecto.Changeset.put_assoc(socket.assigns.changeset, key, value)
Expand Down Expand Up @@ -1419,10 +1418,27 @@ defmodule Backpex.LiveResource do

def get_empty_filter_key, do: @empty_filter_key

defp update_item(socket, item) do
items = Enum.map(socket.assigns.items, &if(&1.id == item.id, do: item, else: &1))
defp update_item(socket, %{id: id} = _item) do
%{assigns: %{live_action: live_action} = assigns} = socket

fields = filtered_fields_by_action(fields(), assigns, :show)
item = Resource.get(assigns, &item_query(&1, live_action, assigns), fields, id)

socket =
cond do
live_action in [:index, :resource_action] ->
items = Enum.map(socket.assigns.items, &if(&1.id == id, do: item, else: &1))

assign(socket, :items, items)

live_action == :show ->
assign(socket, :item, item)

assign(socket, :items, items)
true ->
socket
end

socket
end

defp refresh_items(socket) do
Expand Down

0 comments on commit d3dc342

Please sign in to comment.