sodapopcan
Confusion around LiveView initial render/using a map in assigns
To get to the crux of this question right away: Does LiveView always do a first render without any assigns?
So I’m using a struct as one of my assigns. Imagine I’m the url being something like https://mydomain.com/some_id:
defmodule MyAppWeb.HomeLive do
use MyAppWeb, :live_view
@default_assigns [
record: nil, # The default here will never be used, hence `nil`. I tried giving it a default and it doesn't solve my problem.
another_key: "that has a dynamic value but needs a default"
]
def mount(%{"record_id" => record_id}, _session, socket) do
record = Records.find_record(record_id)
{:ok, assign(socket, @default_assigns |> Keyword.replace!(:record, record))}
end
end
Then in my template:
<div><%= @record.some_key %></div>
No matter what, even though my page loads seemingly without a hitch, I always get an error that “nil.some_key is not a function”.
I can, of course, fix this with:
<div<%= @record && @record.some_key %></div>
but I’m confused about the lifecycle here… does the template always render once without been passed any assigns? OR am I just doing something completely wrong?
Thanks!
Most Liked
sodapopcan
Thank you both for your responses. I realize it’s because I’m doing something pretty cavalier that isn’t well represented in my sample code. It’s because my route matches on any root path, so /:record_id. This of course means that requests for favicon.ico is matching ![]()
hectorsq
Hi,
The first param for assign should be a socket.
{:ok, assign(socket, @default_assigns |> Keyword.replace!(:record, record))}
hectorsq
You also defined @defaul_assigns (missing t) and are using @default_assigns
No, the first render uses the data in assigns that is initialized in mount
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








