How do I reset form input on submit?

My form:

 def mount(socket) do
    {:ok,
     socket
     |> assign(:form, to_form(%{"input_msg" => ""}))}
  end

 <.form for={@form} phx-target={@myself} phx-submit="save" class="w-full flex gap-2">
        <.input
          field={@form[:input_msg]}
          autocomplete="off"
          name="message"
          type="text"
        />
....

And the submit function ends like this:
{:noreply, socket |> assign(:form, to_form(%{"input_msg" => ""}))}

render/1 is not called after this, even though socket should be changed.
What am I doing wrong?

Thanks.

1 Like

You aren’t changing the value of the assign, so from the framework’s point of view nothing has changed so there is no need to re-render. Add a phx-change="change" on the form and update the form assign.

Any particular reason you are giving the input name="message"?

You can probably just pass an empty map to to_form to clear the value.

3 Likes

Thanks @cmo adding phx-change fixed it.

I’m learning phx
I had same issue and solved it, but still do not get following sentence

from the framework’s point of view nothing has changed so there is no need to re-render

It looks to me that assigns.form.input_msg has been changed from last input to empty string.

Can i get more hint on this?

On mount, the form has an empty string for input_message. There is no phx-change event, so the assign is not changed when the user types in the input. When submitted, the form is reassigned with the value that already exists in there. The framework doesn’t see any change in that value, so sees that nothing needs rerendering.

If a change event is added and the form assign updated with the user input in the handle_event callback, the form assign will have changed so when the form is submitted the assign will be different and “reset” the form input. i.e. ensure the server state reflects the client state.

1 Like

wow excellent explanation!

now i am worrying about too much network roundtrip by updating state whenever user input any character though

I do not recommend you do it on each keypress, unless you have a special case where it is required. See how to limit here:

https://hexdocs.pm/phoenix_live_view/bindings.html#rate-limiting-events-with-debounce-and-throttle

2 Likes