Arsenalist
How to set value in on_mount which can be read in LiveView?
I have the following live session:
scope "/live", AmplifyWeb do
live_session :default,
layout: {AmplifyWeb.Layouts, :admin},
on_mount: AmplifyWeb.Live.TokenValidator do
live "/mailing-lists/:mailing_list_id/import-subscribers", ImportSubscribers
live "/events/performance", EventPerformance
end
end
I want to validate a token from the query string in TokenValidator.on_mount and store the user_id from it in session so that it is available to all LiveViews within the live_session.
However, when I set anything on socket or session in on_mount, it is not available in the LiveView. I understand that’s because they are different instances of socket which makes sense. But how do I go about reading an initial value from query string and keeping it around in session or somewhere else where it can persist across LiveViews in the same live_session (and persist it across refreshes)?
Marked As Solved
sodapopcan
No prob, no matter how easy frameworks make stuff, web programming is the worst (even though I like it) ![]()
It’s actually best to do it in a plug since you can’t write session data over web sockets (this is a limitation of web sockets, not LiveView). I would make a new project and run mix phx.gen.auth Accounts User users and look at the UserAuth module. The short answer is that you want, Plug.Conn.put_session though. Basically move that whole initial validation logic to a plug and then your on_mount can always read from the session.
Sorry I can’t point you to anything that implements actual API auth.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









