LiveView's Automatic Form Recovery ⚡️

I don’t know about you, but I hate it when I’m filling out a long form and for some reason it disconnects, reconnects and I lose all of my form data. 😱

Thankfully LiveView ships with automatic form recovery through phx-change attributes.

Say we have a form with something like phx-change=“validate”. When LiveView reconnects, it will automatically send a phx-change event with the latest data.

You can try that in your browser. Type in a form field (say, “ABC”). Then disconnect and reconnect your server.

If you don’t have a phx-change attached to the form, your form will clear as the page re-renders. But if you have a phx-change, you’ll see the form keep the data (assuming your phx-change is setting the form’s assigns).

You can also confirm that by looking at your server logs. You should see that after the reconnect, we have a handle_event ”validate” call that comes in.

But what happens if you want to do special recovery? Maybe you need something different than just your normal validation (or whatever your phx-change event was doing)?

Well, Phoenix ships with a really cool binding phx-auto-recover! 🥳

Add it to your form and pass it a new event.

<.form for={@form} phx-change="validate" phx-auto-recover="recover" ...>

Now, the "recover" event will be sent instead of the ”validate” event! (Of course, don’t forget to handle the new event appropriately.)

Want the latest Elixir Streams in your inbox?

    No spam. Unsubscribe any time.