jononomo
I'm confused about "assigns" what does it do?
Can anyone point me to some resources to understand the “assigns” functionality. I see it used in Phoenix Channels, but am not sure what is happening under the hood. Thanks.
Most Liked
josevalim
Imagine you want to pass some value from your join function in channels to handle_in. You cannot simply assign to a variable:
def join(..., socket) do
username = "hello"
{:ok, socket}
end
def handle_in(..., socket) do
username #=> this will raise
end
So instead, we store it in a data-structure (or assign it to a data structure) and pass the data structure forward:
def join(..., socket) do
socket = assign(socket, :username, "hello")
{:ok, socket}
end
def handle_in(..., socket) do
socket.assigns.username #=> this works
end
The field in itself is a map with atom keys and the stored values.
LostKobrakai
“Assigns” is basically the data backpack of the socket or Plug.Conn connection. You’d use it to hold onto data, which you’ll need throughout the lifetime of that connection. One example would be the authentication status (current user). It’s kinda like the session mechanic for http requests, but the session is used to store data between multiple request, while assigns store data for usage within a single request.
dom
Channels are processes (GenServer), so they have a state, which is the Socket struct. “assigns” is one field of that struct which Phoenix provides for you to store app-specific data. For instance you could store a user ID in assigns when the channel is created (join), then access it later when you receive messages (handle_in), in order to tell who sent it. It’s a plain old map.
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









