diff --git a/lib/backpex/live_resource.ex b/lib/backpex/live_resource.ex index b96b3005..f2f86e45 100644 --- a/lib/backpex/live_resource.ex +++ b/lib/backpex/live_resource.ex @@ -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) @@ -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