Hasimbola
Update Session inside liveview
Hello everybody, did someone know how to update session inside liveview?
Thanks! ![]()
Most Liked
msimonborg
You have to make a HTTP request to a controller to mutate the session cookie. It is possible to do without navigating away from your live view, but YMMV and you’ll have to decide if this works for your use case.
In my case, I want to update certain user settings in the session. It is possible to target a form submission to a hidden iframe, so you can submit a form through the iframe without reloading your page. There’s a little extra setup, but you can use this with live view.
I place the iframe at the bottom of my live layout:
<!-- This iframe provides a target for hidden form submissions and HTTP requests -->
<!-- that mutate the session state. -->
<iframe hidden name="hidden_iframe" src={Routes.iframe_path(@socket, :index)} height="0" width="0">
</iframe>
It needs a src so I have an /iframe route with a simple controller action that just returns html(conn, "ok"). Of course this means it’s making an extra HTTP request to your server every time you load a page that contains this iframe. Then create your form targeting the hidden_iframe
<.form
let={f}
for={:settings}
action={Routes.settings_path(@socket, :update)}
method="put"
target="hidden_iframe"
>
In my case, my SettingsController does as little as possible, it validates the input with an embedded changeset, updates the session, and returns html(conn, "ok") or html(conn, "error: #{errors}")
LostKobrakai
If it’s for preferences (non personal data) a separate cookie (non http-only) could be used with push_event to customize from JS.







