Handle Change

Learn how event handlers work in Phoenix.

The ProductLive.Index LiveView also supports the Product Edit and Product New features by using the change management workflow to alter the socket state with event handlers. In this way, a single LiveView can easily handle multiple pieces of CRUD functionality.

We’ll examine the change management workflow now, starting with the Product Edit functionality.

How to route to the Product edit

Let’s trace the code that fires when we point our browser at the /products/:id/edit route, starting with the route definition.

The router contains the following generated route for the Product Edit feature:

Press + to interact
live "/products/:id/edit", ProductLive.Index, :edit

This maps the /products/:id/edit route to the same ProductLive.Index LiveView that we examined earlier but with a live-action of :edit. By specifying a live-action in the route definition, LiveView adds a key of :live_action to the LiveView’s socket assigns, setting it to the value of the provided action.

To take advantage of this live-action to change the LiveView’s state, we’ll look into a slightly different LiveView lifecycle than we saw for mount/render.

When we navigate to the Product Index route, /products, the LiveView lifecycle that kicks off first calls the mount/3 lifecycle function, followed by render/1. If, however, we want to access and use the live-action from the socket assigns, we must do so in the handle_params/3 ...