LiveView toggle between views by a cookie setting

as an option, you can rely solely on LiveView and cookie/localstorage to determine what are user selected settings, but it has downsides of course.

What you can do is to send the data from localstorage or cookie from javascript, during LiveView initialization.

let liveSocket = new LiveSocket('/live', Socket, {
  params: {
    _csrf_token: csrfToken,
    saved: getFromLocalstorage('saved', []), // this is additional thing that you are sending  to your LiveView
  },
  hooks: hooks,
});

You can later access this value from mount function in LiveView with get_connect_params(socket) (I actually had similar question not long time ago How to send data from localstorage to LiveView on initial load)

There is a downside however, you will not have access to the data from localstorage on server on the inital load.
What will happen is that client will make a request to your website. It will get back initial render of the page (together with all assets, js etc). Since, the connection to LiveView happens only after js code is loaded, your initial data from localstorage will be sent to server only at that point.

For your case, it will mean that, initially, page with table(let’s say that’s default) will be loaded, then page will send settings from localstorage/cookie to server and LiveView will rerender. It happens quite fast, but you will see flicker for sure. so if user configured it to be a list, there will be table and then switch to list in a course of few seconds of initial load. To avoid that, you can of course have some kind of spinner(which partialy defeats the purpose, of not going with SPA). Not sure, if it will suite your use case, for me it was perfect, because showing loading on initial load was not something bad for my use case. Basically, It works really well, if it is not the first page of your application

2 Likes