coen.bakker

coen.bakker

Form in live component not resetting on phx-submit

This must be something minor, but I can’t seem to put my finger on it. Why are the values of the <.form> not reset on a successful phx-submit?

defmodule AppWeb.SomePageLive
  def render(assigns) do
    ~H"""
      <.live_component
        id="some-id"
        module={AppWeb.PostingBarComponent}
        topic={@selected_topic}
        user={@current_user}
      />
    """
  end
end
defmodule AppWeb.PostingBarComponent
  use Phoenix.LiveComponent
  use AppWeb, :html
  import Phoenix.HTML.Form

  def mount(socket) do
    {:ok, assign(socket,
      post_draft: to_form(empty_changeset())
    )}
  end

  def render(assigns) do
    ~H"""
    <div>
      <.form
        for={@post_draft}
        id="form-id"
        phx-submit="submit_post"
        phx-target={@myself}
      >
        <%= textarea(@post_draft, :content,
          id: "post-input",
          rows: 1,
          placeholder: "Post to ##{@topic.name}"
        ) %>
        <button type="submit">Submit</button>
      </.form>
    </div>
    """
  end

  def handle_event("submit_post", %{"post" => post}, %{assigns: assigns} = socket) do
    %{topic: topic, user: user} = assigns
    %{"content" => content} = post

    case App.Social.create_post(content, topic.id, user.id) do
      {:ok, _} ->
        {:noreply, assign(socket,
          post_draft: to_form(empty_changeset())
        )}

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

  defp empty_changeset() do
    %App.Social.Post{}
    |> Ecto.Changeset.change()
  end
end

First Post! Switch mode

coen.bakker

coen.bakker

Is seems like {:noreply, assign(socket, post_draft: to_form(empty_changeset()))}, after a successful submit, is not triggering the expected component rerender.

Most Liked

ahallock

ahallock

I ran into this problem the other day. The only good solution I found was to use phx-change as you suggested. Another thing that worked was assigning a random ID – to_form(id: my_random_id) – to the form but that feels like a hack.

coen.bakker

coen.bakker

I opted for adding a private function that randomizes the ids, thanks.

  defp to_unique_form(changeset) do
    to_form(changeset, id: "form-#{System.unique_integer()}")
  end

  defp empty_changeset() do
    %App.Social.Post{}
    |> Ecto.Changeset.change()
  end
sodapopcan

sodapopcan

You definitely do not want to do this as it could have unintended consequences on change tracking. I had this idea before and was swiftly reminded that this was the case!

Last Post!

UncountedSphere

UncountedSphere

I tried a couple of things, and changing the id is the only thing that worked for:

 def handle_event("add", %{"entry" => params}, socket) do
    case Paste.Entries.create_entry(params) do
      {:ok, entry} ->
        {:noreply,
          socket
          |> put_flash(:info, "entry #{entry.id} added")                                                
          |> assign(
           form: to_form(
             Entries.change_entry(%Entry{}),
             id: "form-#{System.unique_integer()}"
           )
          )
          |> stream_insert(:entries, entry, at: 0)}

      {:error, %Ecto.Changeset{} = changeset} ->
        {:noreply, assign(socket, form: to_form(changeset))}
    end
  end

Where Next?

Trending in Discussions Top

AstonJ
As the title says, please share what you’ve been up to with Elixir. Whether that’s been learning it, looking into it, making stuff with i...
2976 91332 914
New
byu
@chrismccord : I just saw the Extract AGENTS.md from Phoenix.new into phx.new generator commit to the phoenix project. My initial shotgu...
New
arcanemachine
I was working on an Ecto migration and I needed a timestamp. So, for the nth time, I looked up the different data types for timestamps, a...
New
AstonJ
Just a general thread to post chat/news/info relating to AI/ML stuff that may be relevant for Nx now or in the future. Got anything to sh...
New
type1fool
I just stumbled on a newly redesigned elixir-lang.org. :tada: It looks like @Software_Mansion did the work, and I think it is generally a...
New
juhalehtonen
There has been a thread to discuss the Stack Overflow Developer Survey on this forum every year since 2018, so here’s yet another one for...
New
alexslade
Fly’s CEO posted this recently - Turn And Face The Strange · The Fly Blog It says that Fly is going all-in on sprites, which is a worry ...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
akoutmos
@hugobarauna and I (Alex Koutmos) have been hard at work on writing a book on Nerves that takes you from simply blinking LEDs to building...
New
zachdaniel
Introducing AshStorage! Attachment and file management that slots directly into your resources :smiling_face_with_sunglasses: I had hope...
New

We're in Beta

About us Mission Statement