<turbo-stream action="append" target="posts_list"><template>    <div class="postbit" id="375774" data-post-id="375774">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="bartblast" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/bartblast/120/17647_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  bartblast
                  </h3>
		          </div>
						
			          <div class="user-title">
									<span>Creator of Hologram</span>
			          </div>
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<aside class="quote no-group" data-username="garrison" data-post="11" data-topic="65037">
<div class="title">
<div class="quote-controls"></div>
<img alt="" width="24" height="24" src="https://forum.elixirforum.com/letter_avatar_proxy/v4/letter/g/3bc359/48.png" class="avatar"> garrison:</div>
<blockquote>
<p>This also means that <a class="mention" href="/u/bartblast" rel="nofollow">@bartblast</a> should take note, as if he implements controlled inputs correctly this is a case where Hologram will just be strictly and unavoidably better.</p>
</blockquote>
</aside>
<p>Yeah, this is already solved in Hologram since v0.6.0 <img src="https://forum.elixirforum.com/images/emoji/apple/slight_smile.png?v=15" title=":slight_smile:" class="emoji" alt=":slight_smile:" loading="lazy" width="20" height="20"> It’s called “synchronized inputs” and it works in a similar lock-step fashion - the component state is always the single source of truth, and input values are kept in sync declaratively through unidirectional data flow.</p>
<p>Check out the docs here: <a href="https://hologram.page/docs/forms" rel="noopener nofollow ugc">https://hologram.page/docs/forms</a></p>
<p>Forms: <img src="https://forum.elixirforum.com/images/emoji/apple/white_check_mark.png?v=15" title=":white_check_mark:" class="emoji" alt=":white_check_mark:" loading="lazy" width="20" height="20"> solved!</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="375774" data-batch-url="/posts/batch_likers">
                        1
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/form-doesnt-always-get-cleared-after-submitting/65037/12">Post #11</a>
	                </div>
	            </div>
              <div id="likers-container-375774" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="375774"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #11"></div>
  </section>
</div>
    <div class="postbit" id="375897" data-post-id="375897">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="rhcarvalho" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/rhcarvalho/120/32243_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  rhcarvalho
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<aside class="quote no-group" data-username="garrison" data-post="11" data-topic="65037">
<div class="title">
<div class="quote-controls"></div>
<img alt="" width="24" height="24" src="https://forum.elixirforum.com/letter_avatar_proxy/v4/letter/g/3bc359/48.png" class="avatar"> garrison:</div>
<blockquote>
<p>What is actually going on here is that LiveView’s declarative abstraction is fundamentally leaking its imperative implementation. This is the sort of bug that is <em>not supposed to happen</em> with a declarative programming model.</p>
</blockquote>
</aside>
<p>You’re always spot on with your insights <a class="mention" href="/u/garrison" rel="nofollow">@garrison</a>, thanks for chiming in!</p>
<hr>
<p>I would like to offer a hint for others (and myself in the future) with a possible path forward. First, summarizing the issue:</p>
<h2><a name="p-375897-issue-summary-1" class="anchor" href="#p-375897-issue-summary-1" aria-label="Heading link" rel="nofollow"></a>Issue summary</h2>
<h3><a name="p-375897-server-state-didnt-change-2" class="anchor" href="#p-375897-server-state-didnt-change-2" aria-label="Heading link" rel="nofollow"></a>Server state didn’t change?</h3>
<ol>
<li>A form has <code>id</code>, <code>phx-change</code>, <code>phx-submit</code> and <code>phx-debounce</code>. The latter makes it more likely that a submit event may reach the server before any change event, but I believe is not fundamental to trigger the issue.</li>
<li>The initial form state is something like <code>to_form(%{})</code>.</li>
<li>The user submits the form, say with some text input with value <code>"hello"</code>.</li>
<li>The server handles the submit event and responds with what is intended to be an empty form, again <code>to_form(%{})</code>.</li>
<li>From the server’s perspective, there was no change, so no reason to re-render the text input.</li>
<li>The text <code>hello</code> remains visible <img src="https://forum.elixirforum.com/images/emoji/apple/bug.png?v=15" title=":bug:" class="emoji" alt=":bug:" loading="lazy" width="20" height="20"> <img src="https://forum.elixirforum.com/images/emoji/apple/beetle.png?v=15" title=":beetle:" class="emoji" alt=":beetle:" loading="lazy" width="20" height="20"> <img src="https://forum.elixirforum.com/images/emoji/apple/cricket.png?v=15" title=":cricket:" class="emoji" alt=":cricket:" loading="lazy" width="20" height="20"></li>
</ol>
<p>So in previous messages in this thread we talked about the “no change from the server’s perspective”. There’s a little bit more into play here, for which I refer to the LiveView documentation:</p>
<h3><a name="p-375897-liveview-js-client-specifics-3" class="anchor" href="#p-375897-liveview-js-client-specifics-3" aria-label="Heading link" rel="nofollow"></a>LiveView JS client specifics…</h3>
<ul>
<li><a href="https://hexdocs.pm/phoenix_live_view/syncing-changes.html#the-problem-in-a-nutshell" class="inline-onebox" rel="noopener nofollow ugc">Syncing changes and optimistic UIs — Phoenix LiveView v1.2.5</a></li>
<li><a href="https://hexdocs.pm/phoenix_live_view/form-bindings.html#javascript-client-specifics" class="inline-onebox" rel="noopener nofollow ugc">Form bindings — Phoenix LiveView v1.2.5</a></li>
</ul>
<blockquote>
<p>The JavaScript client is always the source of truth for current input values. For any given input with focus, LiveView will never overwrite the input’s current value, even if it deviates from the server’s rendered updates.</p>
</blockquote>
<p>So even if in step <strong>4</strong> above we’d assign <code>to_form(%{content: "some other value"})</code>, LiveView would still not update the visible input value (assuming it would be focused when submitting the form).</p>
<h2><a name="p-375897-possible-solution-4" class="anchor" href="#p-375897-possible-solution-4" aria-label="Heading link" rel="nofollow"></a>Possible solution</h2>
<p>After evaluating a few options, I decided to go with a “pessimistic UI update” in my particular case. It means I want the client to clear the input only after the event is handled in the server and there were no validation errors, etc.</p>
<p>Eventually, the change is small but combines different concepts, so I decided to share.</p>
<ul>
<li><code>push_event/3</code> to send (JS) events from server to client, only in the success path.</li>
<li>Global JS event listener to set DOM properties (unlike the <code>JS.set_attribute/3</code> command that works on HTML attributes).</li>
</ul>
<pre data-code-wrap="elixir"><code class="lang-elixir">defmodule MyApp.MyLive
  def render(assigns) do
    ~H"""
    &lt;.form
      for={@form}
      id="my-form"
      phx-change="validate"
      phx-submit="send"
      phx-debounce
      class="phx-submit-loading:opacity-50"
    &gt;
      ...
    &lt;/.form&gt;
    """
  end

  # ...

  def handle_event("send", %{"message" =&gt; message}, socket) do
    socket =
      case send(message) do
        {:ok, message} -&gt;
          socket
          |&gt; assign(form: to_form(%{}, as: :message))
          |&gt; clear_input()

        {:error, changeset} -&gt;
          socket
          |&gt; assign(form: to_form(changeset, action: :submit))
      end

    {:noreply, socket}
  end

  defp clear_input(socket) do
    socket
    |&gt; push_event("myapp:setproperty", %{
      "selector" =&gt; "##{socket.assigns.form[:content].id}",
      "property" =&gt; "value",
      "value" =&gt; ""
    })
  end
end
</code></pre>
<pre data-code-wrap="js"><code class="lang-js">// app.js

// Similar to `JS.set_attribute/3` but sets a DOM property instead of an HTML
// attribute. The distinction is important for certain properties like `value`
// on input elements, which do not reflect changes made to the attribute.
// https://forum.elixirforum.com/t/using-liveview-js-to-manipulate-input-values/46371/2?u=rhcarvalho
// https://hexdocs.pm/phoenix_live_view/syncing-changes.html#the-problem-in-a-nutshell
// https://hexdocs.pm/phoenix_live_view/form-bindings.html#javascript-client-specifics
window.addEventListener("phx:myapp:setproperty", event =&gt; {
  const target = document.querySelector(event.detail.selector);
  target[event.detail.property] = event.detail.value;
})
</code></pre>
<h2><a name="p-375897-outro-5" class="anchor" href="#p-375897-outro-5" aria-label="Heading link" rel="nofollow"></a>Outro</h2>
<h3><a name="p-375897-other-possible-directions-6" class="anchor" href="#p-375897-other-possible-directions-6" aria-label="Heading link" rel="nofollow"></a>Other possible directions</h3>
<ul>
<li>
<p>“Optimistic” UI updates with JS commands, like</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">phx-submit={
  JS.push("send")
  |&gt; JS.dispatch(
    "setproperty",
    to: "#field-id",
    detail: %{property: "value", value: ""}
  )
}
</code></pre>
<p>This also works, instantly clears the text input (assuming an event handler for <code>setproperty</code>), and correctly recovers the submitted value in case of a validation error.</p>
</li>
<li>
<p>Client hooks with <code>phx-hook</code>, possibly using the new <code>ColocatedHook</code> in LV 1.1.</p>
</li>
<li>
<p>Listening for the <code>phx:page-loading-stop</code> event as part of the form submit flow.</p>
</li>
<li>
<p>Custom <code>submit</code> handler.</p>
</li>
</ul>
<h3><a name="p-375897-more-on-the-liveview-docs-7" class="anchor" href="#p-375897-more-on-the-liveview-docs-7" aria-label="Heading link" rel="nofollow"></a>More on the LiveView docs</h3>
<p>Quoting <a href="https://hexdocs.pm/phoenix_live_view/form-bindings.html#javascript-client-specifics" class="inline-onebox" rel="noopener nofollow ugc">Form bindings — Phoenix LiveView v1.2.5</a>, emphasis mine:</p>
<blockquote>
<p>The JavaScript client is always the source of truth for current input values. For any given input with focus, LiveView will never overwrite the input’s current value, even if it deviates from the server’s rendered updates. <strong>This works well for updates where major side effects are not expected</strong>, such as form validation errors, or additive UX around the user’s input values as they fill out a form.</p>
</blockquote>
<p>I continued reading the page looking for “conversely, what do I do when <strong>major side effects ARE expected</strong>?” – not found <img src="https://forum.elixirforum.com/images/emoji/apple/slight_smile.png?v=15" title=":slight_smile:" class="emoji" alt=":slight_smile:" loading="lazy" width="20" height="20"></p>
<p>If anyone wants to continue the discussion in this direction we might be able to fill in that gap in the docs together!</p>
<p>Thanks! <img src="https://forum.elixirforum.com/images/emoji/apple/purple_heart.png?v=15" title=":purple_heart:" class="emoji" alt=":purple_heart:" loading="lazy" width="20" height="20"></p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="375897" data-batch-url="/posts/batch_likers">
                        1
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/form-doesnt-always-get-cleared-after-submitting/65037/13">Post #12</a>
	                </div>
	            </div>
              <div id="likers-container-375897" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="375897"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #12"></div>
  </section>
</div>
    <div class="postbit" id="375922" data-post-id="375922">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="LostKobrakai" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/LostKobrakai/120/3072_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  LostKobrakai
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<aside class="quote no-group" data-username="rhcarvalho" data-post="13" data-topic="65037">
<div class="title">
<div class="quote-controls"></div>
<img alt="" width="24" height="24" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/rhcarvalho/48/32243_2.png" class="avatar"> rhcarvalho:</div>
<blockquote>
<p>I continued reading the page looking for “conversely, what do I do when <strong>major side effects ARE expected</strong>?” – not found</p>
</blockquote>
</aside>
<p>Concurrent changes to a shared input value between the client and the server under latency are not trivially handled. You run into all the problems of distributed computing there. Even client side libraries in the past got this stuff wrong - and they didn‘t have a network on the path. LV does.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="375922" data-batch-url="/posts/batch_likers">
                        2
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/form-doesnt-always-get-cleared-after-submitting/65037/14">Post #13</a>
	                </div>
	            </div>
              <div id="likers-container-375922" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="375922"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-last-post cat-last-post" title="Last post!"></div>
  </section>
</div>
</template></turbo-stream><turbo-stream action="replace" target="load-more-container"><template><div id="load-more-container" class="load-more-container">
    <span class="all-loaded">— All posts loaded —</span>
</div></template></turbo-stream>