Jskalc

Jskalc

Phoenix LiveView hot reload has an option to preserve socket state

Sorry if it’s a common knowledge, but it’s something I just learned and wanted to share.

I’ve seen that mind-blowing demo of hot-reload in production recently presented by Chris. So I asked if we could have something like that in development as well: Jakub Skałecki 🚀 #buildinpublic on X: "Hey @chris_mccord could we have this in development? 🧐 Right now state is not preserved across hot reloads" / X

It turns out, it’s there already! In your dev.exs Endpoint config add live_reload: notify section and update live_reload: patterns to match this:

# Watch static and templates for browser reloading.
config :my_app, MyAppWeb.Endpoint,
  live_reload: [
    notify: [
      live_view: [
        ~r"lib/my_app_web/core_components.ex$",
        ~r"lib/my_app_web/(live|components)/.*(ex|heex)$"
      ]
    ],
    patterns: [
      ~r"priv/static/(?!uploads/).*(js|css|png|jpeg|jpg|gif|svg)$",
      ~r"lib/my_app_web/controllers/.*(ex|heex)$"
    ]
  ]

Now when you update your live view code, your state will stay intact.

For me it’s a life-changer. I have to admit I wasted so much time without that feature :smiling_face_with_tear: Mostly when working with a bit more complex Live Views with forms or ephemeral state.

Did you know about it? Is it highlighted somewhere in the documentation / installation instructions but I just somehow missed it? :thinking:

Most Liked

chrismccord

chrismccord

Creator of Phoenix

This has been there for months (years?), but we haven’t been certain how we want to recommend usage yet or include by default. It’s the same considerations as production where you can footgun an upgrade into bad state, ie you introduce a new assign in the template and mount, but the running LV doesn’t have it. That said, the LV will blow up, immediately remount and all will be well, so even in most footgun cases you can get back to working state without intervention. All that said, we need to make folks aware of the tradeoffs in the docs, and potentially have it be opt-in as needed vs always enabled for every LV. I definitely understand the QoL improvement this brings in dev – which was the whole reason we added it :slight_smile:

11
Post #4
chrismccord

chrismccord

Creator of Phoenix

It’s harder than that. The example I gave of a missing assign that immediately crashing and remounts is the happy path which recovers to a good state, but there are other cases where the app can enter a bad state and not crash (ie you setup pubsub subscriptions or other stateful bits in mount that don’t happen for exisitng process, or you have timers that need to fire, or you had timers that were firing but you removed them and their handle_info clauses and they blow up the process at some point in the future. There’s not try/catch here that saves you. It’s less about transient errors which aren’t a big deal in dev and more about breaking apps in confusing ways, especially for folks that don’t really know what’s going on/why. So I think a non remount live reload is best opt-in where folks could add matches in their config for specific files, or some similar mechanism. Of course it’s fine to go all in and manually refresh as necessary if you know what’s going on, but as a general default it’s tricky to allow users to get into confusing or bad state that shouldn’t be possible to happen.

Jskalc

Jskalc

Thanks for explaining! I had a feeling it’s not a new thing.

It gave me a huge productivity boost. Considering how much engagement my tweet received, it was also useful to others.

I understand your reasoning about being careful to set it as a default, but it would be great to raise awareness. I see these hopefully reasonable options:

  1. Set it as a default, and maybe automatically catch re-render errors when hot-updated with missing assign, so console won’t be cluttered by transient errors
  2. Include commented out in the generated config, with a short explanation what it would do.
  3. Mention it either in the installation instructions or LiveReload docs
  4. Make it an CLI option in phx.new generator?

Personally I’d love to see 1) happen, or 2) if 1) is too dangerous. I might help with a PR if needed.

PS. Thanks to that feature, I was able to achieve amazing DX with my up-and-coming LiveVue library (LiveSvelte but for Vue + Vite). Updates both in JS and EX files are reflected instantly, keeping the state intact. It feels like cheating :smiling_face_with_three_hearts:

Where Next?

Popular in Guides/Tuts Top

1player
A question I had when first learning contexts and Ecto was how to expand the default context API to support more flexible queries. Usuall...
New
sergio
Wrote this guide on how to integrate DropzoneJS with Phoenix Liveview. Hope it helps someone out! Woah read that title again, what a ...
New
zachallaun
Hey friends, wanted to share a tiny shell script I’ve been using to start Livebook with easy access to either a running production server...
New
siever
I just wrote a simple guide on how you can setup a productive elixir development environment in vim. Its really easy, just a few steps. ...
New
yeshan333
vfox (version-fox) is a popular general version management tool write in Go, and the plug-in mechanism uses Lua to achieve extensibility....
New
TwistingTwists
This is a thread to note down things/best practices encountered in LiveBeats App as I explore the source code. https://github.com/fly-...
New
marcin
This post is intended to be a guide for others, I was running a remote debugger for the first time and appreciate feedback on how I could...
New
dogweather
I just finished a long process of configuring and debugging a Docker Compose-based dev environment. Several late-night hours! I think I’v...
New
nietaki
Just a quick heads up: There seems to be a bug in Erlang/OTP 21.3, which can cause some errors when making http requests. If you’re using...
New
anuragg
We just published a guide to automatic clustering in Elixir 1.9, with Mix releases and libcluster. The cluster automatically discovers n...
New

Other popular topics Top

hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a > b) do {:ok, "a"} end if (a < b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement