Reputation: 3300
I'm trying to pass a value from the browser (e.g., localstorage) to the server, and make it available as the live template (leex) is mounted and UI view is created. Tried the following only to get the message shown below.
<JS>
let liveSocket = new LiveSocket("/live", Socket, {params: {init_state: "value from localstorage"}..
<Phoenix>
def mount(params, _session, socket) do
IO.inspect(params) # this returns "not route mounted"
Upvotes: 0
Views: 2959
Reputation: 16274
Another solution is to use hooks, which let you call arbitrary JS (such as reading from localStorage) on mount (or other events) and then send a message to the LiveView.
Somewhere in the template:
<div phx-hook="LoadIt"></div>
Modify app.js:
let Hooks = {}
Hooks.LoadIt = {
mounted() {
this.pushEvent("foobar", {
baz: localStorage.getItem("baz"),
})
},
}
let liveSocket = new LiveSocket("/live", Socket, {
params: {_csrf_token: csrfToken},
hooks: Hooks,
})
In your LiveView:
def handle_event("foobar", %{"baz" => baz}, socket) do
# Do whatever with baz.
{:noreply, socket}
end
More example code here: https://thepugautomatic.com/2020/05/persistent-session-data-via-localstorage-in-phoenix-liveview/
It's obviously a bit more work for this specific use case than some other solutions, but if you also want to update that localStorage based on what happens in the LiveView, it may be a good option.
Upvotes: 1
Reputation: 31
def mount(params, _session, socket) do
In LiveView, the first argument named params that you are trying to access is used for query params as well as any router path parameters when you have mounted your LiveView from the router which is not your case since you are calling it from the template. That is why you get the error.
To get the value of init_state that you are passing in the
let liveSocket = new LiveSocket("/live", Socket, {params: {init_state: "value from localstorage"}..
You need to call the get_connect_params/1
something in the line of
def mount(_params, _session, socket) do
init_state = get_connect_params(socket)["init_state"]
IO.inspect(init_state)
end
An important thing to note is that get_connected\1
is only available for use inside the mount function.
Upvotes: 3
Reputation: 3300
get_connect_params/1
appears to be the way to do it according to this issue page (https://github.com/phoenixframework/phoenix_live_view/issues/204). Also it's the socket
parameter, not params
to look for the variable under.
<JS>
let liveSocket = new LiveSocket("/live", Socket, {params: {init_state: "value from localstorage"}..
<Phoenix>
def mount(_params, _session, socket) do
IO.inspect(get_connect_params(socket)["init_state"])
Upvotes: 4