orsinium

orsinium

Preserve params when push_patch from handle_event

I have 2 live components on the same page, one for pagination and another for search. Both write their state into URL query params which are later handled by the live controller.

Pagination component:

def handle_event("pagination", %{"page" => _} = params, socket) do
  path = ITJWeb.Router.Helpers.live_path(socket, ITJWeb.OffersLive, params)
  socket = push_patch(socket, to: path)
  {:noreply, socket}
end

Search component:

def handle_event("offer_search", %{"search" => search}, socket) do
  path = ITJWeb.Router.Helpers.live_path(socket, ITJWeb.OffersLive, search)
  socket = push_patch(socket, to: path)
  {:noreply, socket}
end

Controller:

def mount(params, _session, socket) do
  {:noreply, socket} = handle_params(params, nil, socket)
  {:ok, socket}
end

def handle_params(params, _uri, socket) do
  ...
  {:noreply, socket}
end

The issue is that each component resets all existing query params. In other words, when you change the page, the search gets reset. There is a live demo: itj.orsinium.dev/offers.

The issue is that live_path requires all query params to be explicitly passed as a third argument but the existing query params (if I understand correctly) are not passed into handle_event.

  1. Is there a way to get current URL query params inside handle_event?
  2. Is there a way to do live_path + push_patch with preserving the current URL query params?
  3. Should I approach the whole problem differently? Is handle_event of a live component a good place to modify URL or should I delegate it to the controller somehow?

Marked As Solved

Sleepful

Sleepful

I did hit this, so now just use:

<.simple_form for={@form} action={~p"/"} >

instead of

<.form for={@form} action={Routes.home_path(@conn, :action, params)} >

and the :action from verified_route is whatever you defined in the router for that path

Also Liked

cmo

cmo

That’s certainly not the case. I have a LiveView that I set myriad URL query params on and they don’t get overridden. Though I keep the params in assigns so maybe I’m telling a fib :slight_smile:

When you’re using the URL query params, you use handle_params to handle assigning anything that is associated with them. You don’t assign or update them elsewhere (i.e. in handle_event or handle_info). If you want to change them, you use push_patch.

You might find Sophie’s article on the topic useful, though she doesn’t seem to use push_patch.

  def self_path(socket, extra \\ %{}) do
    Routes.live_path(socket, __MODULE__, Enum.into(extra, socket.assigns.params))
  end

  defp patch(socket, extra) do
    push_patch(socket, to: self_path(socket, extra))
  end

  def handle_params(params, _uri, socket) do
    {
      :noreply,
      socket
      |> assign_params(params)
      |> assign_page(params)
      |> assign_search(params)
      |> assign_results()
    }
  end

  defp assign_params(socket, params) do
    assign(socket, :params, Map.take(params, ["page", "search"]))
  end

  defp assign_page(socket, %{"page" => page}) do
    assign(socket, :page, String.to_integer(page))
  end

  defp assign_page(socket, _params) do
    assign(socket, :page, 1)
  end

  def handle_event("submit", %{"search" => search_string}, socket) do
    {:noreply, patch(socket, search: search_string, page: 1)}
  end

  def handle_event("goto_page", %{"number" => number}, %{assigns: %{page: page}} = socket) do
    number = String.to_integer(number)

    if number == page do
      {:noreply, socket}
    else
      {:noreply, patch(socket, page: number)}
    end
  end
cmo

cmo

Or writing them as Function Components. Then you handle the event in the liveview. None of your components are managing their own state so could be Function Components.

orsinium

orsinium

I see that people resurrected this thread with the release of Phoenix 1.7. So, probably, I should provide a final solution to it.

What I ended up doing is explicitly re-add search params to the new path when updating the page number:

https://github.com/orsinium-labs/itj/blob/2a27e8bbe3d2a2a3702b8a1b9cce39622b0374e6/lib/itj_web/components/pagination.ex#L9-L12

And I do not re-add the page number when the search is updated because I want to get the user to the first page when they change the parameters anyway.

So, this solution is a bit messy (because the pagination component must know about all other components that change the page parameters, which is a good example of bad coupling) and you should avoid doing that in big projects. That was good enough for a small pet project, though.

People here (@cmo and @Sleepful) say that in Phoenix 1.7 verified routes should preserve GET parameters. I can’t check it right now (the project is still on Phoenix 1.6), so I’ll mark it as the answer. Feel free to drop a message in the thread if it doesn’t work for you.

Where Next?

Popular in Questions Top

Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&amp;query=perfume&amp;page=2, I would like to get: ...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
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
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: The documentation above suggests that while ...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New

Other popular topics Top

WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
985 43657 311
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
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
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
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

We're in Beta

About us Mission Statement