Sanjibukai

Sanjibukai

LiveView: How to push_redirect in mount (without full page reloads)?

Hi everybody,
TL;DR: How to push_redirect in mount without a full page reload?

I have an application that handle localization with Gettext and I have a plug that set the selected locale in a cookie and in the session.

Now, say I have the following routes:

    live "/:locale", DashboardLive
    live "/product", ProductLive
    live "/cart", CartLive

Sometimes from the other live views I want to go back to the Dashboard, but I don’t want to track anymore the locale. So I have live_redirect links to "/" instead of for example "/en":

# In LiveView, e.g. product_live.html.leex
live_redirect "Home", to: Routes.live_path(@socket, MyApp.DashboardLive, "")

In my Dashboard mount however I want to redirect back to "/en" (or whatever is the current locale) but without refreshing the page.

Currently I have the following code in mount:

def mount(params, session, socket) do
    locale = params["locale"] || socket.assigns[:locale] || session["locale"]
    ...
    # In case of the current path being "/"
    socket = if params["locale"] == nil do
      push_redirect(socket, to: "/#{locale}")
    else
      socket
    end

    {:ok, socket}
  end

Here the code might not be idiomatic, but in my current code I also handle the case where the locale is not in the known locale list but removed for brevity…

The problem is that, I’m getting a full page reload at one moment, but I don’t know where?

If in the views I have the links with the locale, e.g.

# In LiveView, e.g. product_live.html.leex
live_redirect "Home", to: Routes.live_path(@socket, MyApp.DashboardLive, "en")

I can go back and forth within the LiveViews without full reloads.

So I wonder what I’m doing wrong?

Also, the redirect seems to happen after a little delay.
I mean, when I look in the network panel of the devtools, at first it seems that the redirect is actually happening within live views without HTTP full reloads, but after a second or two I got a full page reload..

Edit: At first I tried to use push_patch, but it seems that’s impossible to call push_patch in mount. I got the error attempted to live patch while mounting

Most Liked

Sanjibukai

Sanjibukai

Hello,

I reply to myself since I found a solution..
I simply do a push_patch but in handle_params and it works!

I still set the locale in assigns in mount, but now I have the following:

def handle_params(%{"locale" => _locale}, _url, socket) do
  {:noreply, socket}
end
def handle_params(_params, _url, socket) do
  {:noreply, push_patch(socket, to: "/#{socket.assigns.locale}")}
end

In the meantime I saw that it’s possible to check for existence (or absence) of keys in map from elixir 1.10.
So the following is also applicable.

def handle_params(params, _url, socket) when not is_map_key(params, "locale") do
  {:noreply, push_patch(socket, to: "/#{socket.assigns.locale}")}
end
def handle_params(_params, _url, socket) do
  {:noreply, socket}
end

I wanted to know which one do you prefer and think that it’s the most idiomatic elixir?
I want to say that both are idiomatic since there are both pattern matches.

I tend to prefer the second one in which what I want to do (push_patch) is explicit and matched on the guard I want (absence of key)

In the first one it’s implicit. I mean in the match I’m doing nothing, and then I do what I want in the default fallback match..

Anyway..

Have a nice day..
And happy elixir 1.11 ! (even if it’s still RC)

Where Next?

Popular in Questions Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
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
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

Other popular topics Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
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
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New
vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New

We're in Beta

About us Mission Statement