tnederlof
I have been playing around with the new Phoenix Auth generator (https://github.com/aaronrenner/phx_gen_auth) and have been learning a lot just reading through the design/code of the files generated so thank you to anyone who worked on it, impressive! My question is what are the best practices for working with the current user in a liveview .ex file.
When using live view I often want to display a list of items that belong to a certain user. In my item context I have a function set up to talk to ecto and list out items that are associated with a certain user_id.
Items.list_user_items(user) for example.
In order to get the user to feed the function I have found this following code works in the mount call.
def mount(_params, session, socket) do
user = Accounts.get_user_by_session_token(session["user_token"])
{:ok, assign(socket, :items, Items.list_user_items(user))}
end
However in a function like handle_event that does not have the session, how would I properly pass the current user to the list_user_items function?
def handle_event("delete", %{"id" => id}, socket) do
item = Items.get_item!(id)
{:ok, _} = Items.delete_item(item)
{:noreply, assign(socket, :items, Items.list_user_items(**user**))}
end
Trending in Questions
Other Trending 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
- #blog-post
- #phoenix_html
- #iex
- #graphql
- #ai
- #genstage
- #elixirconf-us
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #security
- #hex










First 4 of 4 Posts
idi527
You’d probably store the
current_userin assigns inmountso that it’s accessible atsocket.assigns.current_userin other callbacks likehandle_event.You can also create a helper like
assign_mountin which you’d assign the user to the socket if you need it in more than one liveivew.tnederlof
Ha that might have been the quickest answer, kind of embarrassed that didn’t occur to me.
Thank you so much for that link, that page is EXACTLY what I need!
unsek
For those who can’t find the page linked by @idi527, it got moved to its own page.
aegatlin
And here’s that same link without the version specified (so it defaults to “latest”)