Live_redirect from a child rendered LiveView

I have multiple LiveView pages (live routes) that all need to render a child LiveView (a date picker for filtering data by date range). I want this child LiveView to be able to use live_redirect in order to change the query params in the url when it is interacted with. However, I’m getting an error saying you can’t use live_redirect in a child rendered LiveView.

I’m pretty new to Elixir, and I can’t find a lot of information on how to accomplish this. I’ve seen other threads saying to use pubsub, but it seems like that is going to lead to a lot of duplicate code as each “parent” component is going to have to subscribe to messages from the child (at least that is my understanding).

Aniy tips on how I can use live_redirect when something happens in a child rendered LiveView?

1 Like

You have to message the parent because the URL is a “single resource”, and if you have two things trying to change it in incompatible ways, your application goes into an inconsistent state.

It doesn’t know to be “use pubsub”, you could do it like:

send(socket.root_pid, {:redirect_to, Routes.foo_bar(...)})

And then handling it in your parent handle_info, but in a nutshell, you should double think if this approach is correct. In particular, double think if you really need two live views (especially with the components features in master - although you will need to check the source to read the docs).


Thank you for the response. It was really helpful.

I realized my mistake. In case anyone ends up here with the same problem I had – I was treating live views much like one would treat react components. However, it occurred to me after reading Jose’s response that I could make a regular .eex component rather than using a live view to accomplish what I was trying to do. I ended up following this tutorial and got things working how I needed them, without having to use a child live view.