LiveView, flashes and redirects

How are others handling the following:

  1. Child components generating flashes (I’ve built a macro to easily send a flash to the root LiveView for display)
  2. Business logic which triggers a flash and redirect (i.e. updating your personal details and returning to the dashboard).

I really don’t have a good solution for “2” yet. Flash messages sent to the root component are never displayed because the root component is unmounted when the redirect is triggered.

One solution that springs to mind is to have two root LiveView components. One for the “pages” and the other which is solely responsible for displaying flash messages. Flashes could then be sent via PubSub subscriptions.

How have others solved this?

Maybe I’m misunderstanding your question, but if I do:

socket
|> put_flash(:info, "You've been redirected to the dashboard")
|> push_redirect(to: "/dashboard")

# push_navigate if you're on LV 0.18

I get redirected to the dashboard and I can see the flash message. Is this what you were looking for?

Hmm, the only difference with your code is I’m triggering the redirect from the child component. Maybe I need to push the flash and the redirect request to the parent component and I’ll get the flash on the destination page.

I wouldn’t even think in terms of the component pushing flash and redirect.

Generally, I don’t think a component should deal with redirecting or showing flash messages. Its concerns should be rendering and managing portions of your page. I would leave high-level tasks to the parent live view.

I would have the component send an event or a message to the parent live view, and have the parent live view react to it, in this case with a redirect and a flash message.

1 Like

That seems reasonable, an “onBlah” style event, similar a bit to React’s pattern. Alright, thanks for letting me bounce some ideas around :grinning:

1 Like