Core_components modal does not work with state

The show property is meant to be used when you must open the modal when the page loads. For instance, if you have a route that leads to a modal open when the navigation happens. That’s why it uses phx-mounted and runs only once.

You actually don’t need to keep the modal state in your LiveView or LiveComponent, since the modal HTML will be there all you need to do is use the show_modal("id") JS command and use the on_confirm to send the event.

Based on your code, you can have something like this:

def mount(_params, _, socket) do
  {:ok, socket}
end

def render(assigns) do
  ~H"""
  <.modal id="delete_confirm"
    on_confirm={
      JS.push("delete_access", value: %{id: "11", type: "section-drag"}) # <--- Send the event when you click OK
      |> hide_modal("delete-confirm") # <--- You don't need this if you redirect from your event
    }
  >
    Are you sure?
    <:confirm>OK</:confirm>
    <:cancel>Cancel</:cancel>
  </.modal>
  <p phx-click={show_modal("delete_confirm")}>open modal</p> # <--- Open the modal
  """
end

def handle_event("delete_access", %{"id" => id, "type" => "section-drag"}, socket) do
  # Do the deletion
  {:noreply, socket}
end

(I’ve added some comments so the code is not valid)

5 Likes