We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
To assign the keys of the map to a socket in Elixir using the assign/3
function, you can use Enum.reduce/3
to iterate through the map and update the socket with each key-value pair.
Let's see how that works. Imagine you have this map as the source:
map = %{
app_env: Application.fetch_env!(:my_app, :app_env),
app_name: Application.fetch_env!(:my_app, :app_name),
app_description: Application.fetch_env!(:my_app, :app_description),
app_url: MapAppWeb.Endpoint.url(),
search_term: ""
}
If we want to assign each key with its corresponding value to the socket, you can use Enum.reduce/3
for doing so:
socket = Enum.reduce(map, socket, fn {key, value}, acc_socket ->
assign(acc_socket, key, value)
end)
There is a shortcut to do this by using the assign/2
function:
assign(socket, map)
This is essentially the same as doing:
socket
|> assign(:app_env, map.app_env)
|> assign(:app_name, map.app_name)
|> assign(:app_description, map.app_description)
|> assign(:app_url, map.app_url)
|> assign(:search_term, map.search_term)
Update: It looks like I made things too complicated. The Phoenix.Component.assign/2
function basically does the same thing. When using it with a connection, you can use Plug.Conn.merge_assigns/2
function. I've updated the code with this shortcut. Thanks to namxam.bsky.social and Michal for pointing this out.
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.