I am working on a Phoenix LiveView v.0.17.7 project based on a tutorial. In the app.js file, the user’s time zone is added to the params like this:
let liveSocket = new LiveSocket("/live", Socket, {
params: {
_csrf_token: csrfToken,
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
}
})
On the server side, the time zone is pulled from the params and assigned to the socket:
def on_mount(:default, _params, _session, socket) do
owner = Application.get_env(:calendex, :owner)
time_zone = get_connect_params(socket)["timezone"] || owner.time_zone
socket =
socket
|> assign(:time_zone, time_zone)
|> assign(:owner, owner)
IO.inspect(socket.assigns, label: "^^^^^^^ socket.assigns in init_assigns.ex")
{:cont, socket}
end
This results in a KeyError:
# key :time_zone not found in: %{name: "Bob Boss"}
Time_zone is not set as a parameter in ‘owner’ in config.sys, so this is not unexpected if time_zone is not being captured by get_connect_params(socket). However, if I change that statement to:
time_zone = get_connect_params(socket)["timezone"]
removing the || operator, then time_zone is assigned correctly, as shown by the inspect and in the terminal, in the parameters:
[info] CONNECTED TO Phoenix.LiveView.Socket in 0µs
Transport: :websocket
Serializer: Phoenix.Socket.V2.JSONSerializer
Parameters: %{"_csrf_token" => PUItOWRBBGoJPUMUUGcjThcxWxcdeiN7b0oH1w73cwzW1TWxAylaVJK9", "_mounts" => "0", "_track_static" => %{"0" => "http://localhost:4000/assets/app.css", "1" => "http://localhost:4000/assets/app.js"},
"timezone" => "America/Chicago", "vsn" => "2.0.0"}
I can view the final app and it’s working, so the code provided using the || operator should work, but it doesn’t for me, which I cannot understand.
Any ideas why this won’t work?
Thanks!