LiveView: View state recovery

I managed to work out a solution for this without using LiveView’s built in form auto-recovery feature, and it turned out to be pretty straightforward. Here are the steps in case anyone else is looking to do something similar:

  1. After playing around a bit with mnesia, I decided to use @lucaong’s CubDB instead because I just needed a very simple persistent KV store. CubDB has been serving that purpose admirably so kudos and thanks to @lucaong.

  2. Added CubDB db to my app’s supervisor:

       {CubDB, data_dir: Application.get_env(:my_app, :cubdb_data_dir), name: MyApp.RecoveryCache}
    
  3. Added a binding for my “selection” event and a handler in my LV module that stores the resulting state:

     CubDB.put(MyApp.RecoveryCache, {:selections, user_id: socket.assigns.current_user.id}, selections)
    
  4. Added some conditional code in the mount handler that checks for existing cache and adds it to the LV assigns:

    socket =
     if connected?(socket) do
       selections =
         CubDB.get(
           MyApp.RecoveryCache,
           {:selections, user_id: socket.assigns.current_user.id}
         )
    
       socket |> assign(selections: selections)
     else
       socket
     end
    

That’s it! Now after making some selections on the page and either deploying the app, restarting the server, or just reloading the page, the previous selections are magically still there! Amazing.

5 Likes