...

/

How to make the Demographic Component Stateful

How to make the Demographic Component Stateful

Let's learn how to convert a stateless component to a stateful component.

We already know that we need to convert our stateless demographic form component into a stateful one. Luckily, it’s easy to make our component stateful. All we need to do is add an :id and then our component will be able to respond to events and manage its own state.

We probably expected a long, involved discussion about stateful components here, but that’s really all there is to it. We add that :id in pento/lib/pento_web/live/survey_live.html.leex, like this:

Press + to interact
<%= live_component @socket,
PentoWeb.DemographicLive.FormComponent,
user: @current_user,
id: "demographic-form-{@current_user.id}"%>

Nice. We simply added the :id to the assigns argument given to live_component/3 and we’re off to the races. LiveView identifies stateful components by their component module and the provided :id. Ecto IDs and other application IDs are fair game as long as that ID is unique to the call to live_component/3 on the given page. It’s also worth noting that the given :id is not used as the DOM ID. If we want to set a DOM ID, it is our responsibility to set it in our template.

Now, we can send events to our demo form, so it’s time to add some handlers. First, we’ll briefly discuss the stateful component lifecycle that we’ll take advantage of in order to manage component state.

How to manage component state

The lifecycle of a stateful component is a little different from the stateless component lifecycle. Whenever live_component is called, a stateless component will invoke mount/1, update/2 and render/1. A stateful component, on the other hand, has an additional callback. On the first render, it will call preload/1 before calling mount/1, update/2 and then render/1. ...