List Ratings

Let's learn how to perform state management in components while loading.

We’ll build a ratings index component that will be responsible for orchestrating the state of all of the product ratings in our survey. This component will iterate over the products and determine whether to render the rating details if a rating by the user exists or the rating form if it doesn’t. The responsibility for rendering rating details will be handled by a stateless “rating show” component and the responsibility for rendering and managing a rating form will be handled by a stateful “rating form” component.

Meanwhile, SurveyLive will continue to be responsible for managing the overall state and appearance of the survey page. Only if the demographic record exists for the user will the SurveyLive LiveView render the ratings index component.

In this way, we keep our code organized and easy to maintain because it is adherent to the single responsibility principle—each component has one job to do. By layering these components within the parent SurveyLive LiveView, we are able to compose a series of small, manageable pieces into one interactive user survey page.

We’ll begin by implementing the RatingsLive.IndexComponent. Then, we’ll move on to the rating show component, followed by the rating form component. Let’s get started.

Building the ratings index component

Our RatingsLive.IndexComponent will be stateless—it doesn’t need to respond to any events. All it needs to do is iterate over products and show a rating or a form accordingly. Additionally, this component won’t need to take advantage of any lifecycle callbacks. We’ll use the default implementation of each callback.

The default mount/1 simply returns the socket, and the default update/2 function takes any assigns we pass in and adds them to the socket. Keep in mind that whether or not you provide an implementation, the lifecycle remains the same: mount/1, then update/2, then render/1.

We create a file, pento/lib/pento_web/live/rating_live/index_component.ex, and entered the following component definition, closing it off with an end like this:

Get hands-on with 1200+ tech skills courses.