Hi! I’m learning Elixir and Phoenix and I’ve just started implementing a few live_view features.
Summary: I’m doing a live_render
after a form submission. And when I refresh the page, the form gets resubmitted.
Detail: In the router.ex
I’m not using any live
routes. I figured I would only use routes to controller functions and do live_render
there for those templates which would need it.
The Index for things
is one of the views I want live, to add a live dates filter and to append new created things on other sessions, all of that which works correctly. ThingLive.Index
module has its mount
function and all, and the leex
template is properly displayed after this live_render
call from the controller:
def index(conn, _params) do
things = fetch()
live_render(conn, ThingLive.Index, session: %{
"user" => conn.assigns.user,
"things" => things
})
end
But from the index you can go and add a new thing, which posts the form (nothing live_view there, just a regular form submission to a controller function create
).
Once the render happens, if I reload the page, the form gets submitted again and this function gets executed. Why does this happens and how can I prevent it?
def create(conn, %{"thing" => thing_params}) do
case Thing.create_thing(conn.assigns.user, thing_params) do
{:ok, _thing} ->
things = fetch()
conn
|> put_flash(:info, "Thing created successfully.")
|> live_render(ThingLive.Index, session: %{
"user" => conn.assigns.user,
"things" => things
})
{:error, %Ecto.Changeset{} = changeset} ->
render(conn, "new.html", changeset: changeset)
end
end