It will (usually) run twice. Once when the http request renders the LV statically and then each time the websocket connection starts, which could also happen multiple times if the connection drops intermittently.
A sorry missed a “not” in your sentence. You can make things work with loading data only in the static view, but you’ll need to make sure the stateful render doesn’t replace the existing data.
There is no data – besides the session – being shared between the static render and the connected renders. You either build the system in a way to not need the assign in the connected render or you need to query the data again.
As I see it, if its cheap to fetch (simple query) then fetch twice.
If not, consider one or more of:
Fetching just a part of the dataset
Cache the query
Only query when connected and not in static.
A key thing missing in this thread is that if you use push_redirect and the other navigation helpers then the websocket connection is maintained. This means that you only do the double render on at the first moment the user goes to the site. After that it can simply do a single render.
Here’s an example from an older thread if you would rather query the db only after connected?(socket) == true. The entire thread is well worth the read and explains the context behind LiveView’s lifecycle architecture/design.
But that would make Google bot and people without JS see nothing and only people with JS would see the connected? websocket part. So, for SEO or sharing on facebook etc. this is not a way to go.
What you should do if possible:
You should be using Cachex, so the second fetch is from cache and not the DB, so it’s faster and you free the db pressure by eliminating one call… and all the others later.
Yep this is true, but if you are behind an authenticated route, which is very often the case, using connected? is a much simpler solution than bringing caching into the mix. Though in general I wouldn’t do caching unless absolutely necessary. If you have a lot of navigates and patches, it’s only when the user first comes to the site that the double render/double db hit will happen. Of course it will happen whenever they refresh or there are any hrefs, but generally speaking it’s not going to be a bottleneck (until it is ).