user20230119

user20230119

I’m currently working on a LiveView project where I have a fairly complex UI with nested components. Specifically, I’m using nested LiveComponents to represent hierarchical data structures. Additionally, I’m leveraging the Process Dictionary (Process.put/2 and Process.get/2) to store and retrieve some state, such as the currently selected child entity.

Here’s a simplified example of what I’m doing:

# LiveComponent
~H"""
...
<.button phx-click="select_child" phx-value-id={@entity.id}>Select</.button>
<.button phx-click="link_child" phx-target={@myself} phx-value-path="parent">Link</.button>
...
"""

def handle_event("link_child", %{"links" => path} = params, socket) do
  id = case Process.get(:selected_child) do
    nil -> ""
    child -> child.id
  end

  socket =
    with {:ok, entity} <-
      MyApp.Entity.update_entity_links(socket.assigns.entity,%{path: path |> List.wrap(), value: id})
      do
        socket |> assign(:entity, entity)
    else
      {:error, error} ->
        error |> dbg()
        socket
    end

  {:noreply, socket}
end
# LiveView
def handle_event("select_child", %{"id" => id}, socket) do
  socket =
    with {:ok, child} <- MyApp.Entity.get_entity_by_id(id) do
      Process.put(:selected_child, child)
      socket |> assign(:selected_child, child)
    else
      {:error, error} ->
        error |> dbg()
        socket
    end

  {:noreply, socket}
end

The nested LiveComponents are used to render and manage parts of the UI, and the Process Dictionary is used to share state between different parts of the LiveView. Are there any pitfalls I should be aware of, or alternative approaches you’d recommend?

Showing Posts 1 to 7

garrison

garrison

Nesting LiveComponents is fine.

Using the process dictionary like that, though, is a very bad idea. You should pass state down explicitly through assigns. If you need to send information between components you can use send() and send_update().

See “Managing state” in the docs.

Schultzer

Schultzer

Why is it a bad idea?

olivermt

olivermt

You sidestep change tracking.

A lot of research was put into this fof the Context provider in Surface and it still has some foot guns.

If you are ok with reattaching yourself to the change tracking lifecycle this can work, but it feels a little bit like working outside and against the framework instead of with it.

Is the goal to avoid the verbosity of a send/send_update cycle?

garrison

garrison

A simple answer would be that it’s not idiomatic in LiveView. The comment above points out the change tracking issues.

There are push-based and pull-based reactive systems (really it’s more of a spectrum). LiveView is more on the push side of things - assigns are marked dirty at assign() time and then the dynamics are re-sent in a batch computation. The point being: diffing actually happens when you call assign(), not at render time. In React for example it’s closer to the other way around (though not exactly - they are both somewhere in the middle of the “spectrum”).

If you start storing state outside of the LiveView system you are playing with fire. Technically in the examples from the OP the assigns are not actually used in the template so it should work, but in practice you often want to update your UI based on what item is selected. If you are passing data around via the process dictionary you can no longer propagate information about which assigns are dirty in each render, and the UI will no longer update properly. It’s bad practice to go down this path.

I’m sure there are situations where if you know exactly what you’re doing you could get away with this, but the OP is asking whether it’s an antipattern, and the answer to that is yes, absolutely.

And I know you’re probably aware of this, but for anyone new who’s happening across this thread: we generally try to avoid using the process dictionary in general. It’s an escape hatch which is there for when you really need it.

garrison

garrison

There is also a more subtle problem here.

If you need to propagate an assign you still have to pass it down through the component tree. Likewise you may want to propagate information via send_update and such. If you mix these things with the process dictionary (as you inevitably would if you take this approach), you could end up observing state changes out of order. In database theory this would be a consistency violation. In reactive programming they call these glitches, for some reason.

I didn’t even know Surface had a Context system (I’ll have to look into it), but I’m curious: does it use the process dictionary? And if so, how does it deal with the above?

user20230119

user20230119 OP

I tried passing the selected_child down nested live_components. The problem I had was @selected_child wasn’t used to render anything, but a diff with a blank string for every nested component would still be sent.

<.live_component
  module={MyAppWeb.Entities.IndexLive.EntityComponent}
  id="root"
  entity={@root}
  selected_child={@selected_child}
/>

olivermt

olivermt

What you want to do is track selected child in parent liveview and send two send_update when it changes.

One that unsets the currently set and one that sets the new.

— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New
ryanwinchester
apply_graft/2 doesn’t rewrite an add_many sub-workflow’s deps on an add step. Grafted jobs cancel with “upstream job was deleted” Version...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews