Return Data via Socket from a LiveView Modal to the Parent Liveview?

I’ve been trying to get a:

socket
|> assign(hash: hash)
|> push_redirect(to: "/parent/ack", replace: true)

that is returned from a modal, to actually have the :hash in the assigns when it gets back to the LiveView.

I’ve also tried push_patch and the “assigned” key and value never make it in the assigns. Feel like I’m missing something simple. Any pointers, or other ways to make this happen?

push_patch should work. Can you show a bit more of your code?

This issue is that assign() doesn’t get back up to the parent LiveView. But passing it as a param in the redirect does.

|> push_redirect(to: "/users/tokens/ack?hash=#{hash}", replace: true)

Right, but I’m using something similar to your example with push_patch and it works, so I think something else might be different.

You might be using a live_component for the modal, in that case assigns are indeed scoped to the component and are not shared with the liveview, but you can send a message to the parent liveview with send(self(), {:update_hash, hash}) and handle it to update the assigns.

# in liveview
def handle_info({:update_hash, hash}, socket) do
  {:noreply, assign(socket, hash: hash)}
end
1 Like

The way I see it, there are 2 options:

  1. Do as @ruslandoga said
  2. push_patch with hash as a query param and handle_params the hash in your LV

Option 2:

# you can push_patch since your within the same LV
push_patch(socket, to: Routes.some_path(socket, :index, hash: hash), replace: true)

# this gets called every time you push/live patch
def handle_params(%{"hash" => hash}, _url, socket) do
  {:noreply, assign(socket, :hash, hash)}
end  

I assume that your modal is in a component. Component assigns are separate from the parent, so the assign doesn’t get passed up. You can push_patch and handle_params will take care of it.

You don’t need to redirect if you simply want to get an assign passed from child to parent. You can send self(), :message and the root LiveView will receive it. There are more details here.

2 Likes