Hi,
I have this LiveView, where I intend to create a new Section
. The problem is that after I submit my form 2 times, it appears the third time without the title input.
def mount(_params, _session, socket) do
new_socket =
socket
|> assign(new_section_form: to_form(%{}))
{:ok, new_socket}
end
def handle_event("create_section", %{"title" => _} = params, socket) do
case Boards.create_section(socket.assigns.board.id, params) do
{:ok, created_section} ->
new_socket =
socket
|> assign(sections: socket.assigns.sections ++ [created_section])
|> assign(new_section_form: to_form(%{"title" => ""}))
{:noreply, new_socket}
{:error, changeset} ->
{:noreply, assign(socket, new_section_form: to_form(%{}, errors: changeset.errors))}
end
end
The initial sections are coming from this hook:
def on_mount(:default, %{"id" => board_id}, _session, socket) do
socket =
socket
|> assign(app_header: true)
|> assign(board: Repo.get_by(Board, id: board_id))
|> assign(sections: Boards.get_sections_from_board(board_id))
{:cont, socket}
end
And here is my HEEX template:
<div class="h-full flex flex-col gap-2">
<ul class="grow pb-2 flex gap-1 overflow-x-scroll csb">
<li :for={section <- @sections}>
<.live_component module={SectionComponent} id={section.id} section={section} />
</li>
<div class="flex flex-col gap-1">
<div
class={[
"w-60 p-1",
"flex flex-col items-center",
"card hover:bg-neutral-200",
"transition-all cursor-pointer"
]}
phx-click={toggle_new_section()}
>
<.icon id="toggle_new_section_icon" class="text-slate-600" name="hero-plus" />
</div>
<.form
id="new_section_form"
class={[
"flex flex-col gap-2",
"w-60 p-2 card hidden"
]}
phx-submit="create_section"
for={@new_section_form}
>
<.input type="text" label="List Title" field={@new_section_form[:title]} />
<.button>Create</.button>
</.form>
</div>
</ul>
</div>
The error is solved when I remove the sections assignment after creating a new one in the handle_event
, but I need to reassign the sections. What could be happening?