Form doesn't always get cleared after submitting

When submitting the form, the inputs should clear once I pass an empty changeset, they dont seem to be doing that if I am successful on the first try.
Heres what I mean

  1. the first time the form was correct, it doesnt get cleaned (unexpected)
  2. then I failed with bad inputs, it doesnt get cleaned (expected)
  3. then I submit a correct version, it does get cleaned (expected)
1 Like

heres a snippet of what I am using, is this expected? Am I missing somthing? Thanks in advance guys!

def handle_event("save", %{"volunteer" => volunteer_params}, socket) do
    case Volunteers.create_volunteer(volunteer_params) do
      {:ok, volunteer} ->
        socket =
          update(
            socket,
            :volunteers,
            fn volunteers -> [volunteer | volunteers] end
          )

        changeset = Volunteers.change_volunteer(%Volunteer{})

        {:noreply, assign(socket, :form, to_form(changeset))}

      {:error, changeset} ->
        {:noreply, assign(socket, :form, to_form(changeset))}
    end
  end

This is a somewhat unintuitive issue. The problem is that the initial value of the form assign is a new Volunteer, which is also the value of the assign after a successful submit. Of course, this makes sense when you want to clear the form to allow another submit with new data. But since the assign never changes to anything else, LiveView does not know that it should rerender things that depend on the assign.

When you attempt an unsuccessful submit, the assign gets updated with the invalid changeset, which fixes the problem. The reason why forms generated with phx.gen work is that they react to phx-change, which updates the assign.

Hopefully that makes sense, I’ve encountered this problem just a few days ago and came to this conclusion.

Yep, that’s correct. Since LiveView stores its state on the server, you have to continuously update the server state as the form changes.

So in this case the only solution is to create and handle a phx-update?

You mean phx-change? phx-update is not an event, it’s an instruction on how to handle DOM patching. But yes, you must handle phx-change to keep track of your form’s state server-side. You could implement some JS to do it client-side, but this would defeat the purpose of LiveView.

Yes! Sorry I meant phx-change, its just to me its so weird to be forced to handle constant changes in order for the form to clear, but I understand, the diffing that LiveView does, doesn’t see a difference so thats why it doesn’t re-render it, thanks!

You can also update another assign with an id for the form. Changing the form id makes the form reset. That way you would also add signal to assigns for „this is now meant to be reset“.

Oh ya that’s a good idea! You don’t get validations then though it doesn’t sounds like OP needs them.