This video is available to students only

Svelte Each Blocks

Using Svelte Each Blocks to Iterate a List

Previously, we set up the LunchMenuAdmin component to fetch data from our back end, but we didn't show the data to users in a friendly format. Since we are fetching an array (a list) of lunchWeek objects, we can use a Svelte each block to loop through the array and update the DOM with the results.

Take the example const myList = ['Apple', 'Orange', 'Kiwi']. We can use a Svelte each block to loop through the array and display the fruit:

This will translate to the following markup for the browser:

Let's apply this concept to our lunchWeekList in LunchMenuAdmin.svelte. Instead of using an unordered list, we'll use a table. The each block will be wrapped around the table rows after the header:

plain-table

It's looking better, but we haven't applied our Bulma table class yet. Just add class="table" to the table element:

Even better, but it's not interactive yet. When an admin user views this data, they will need to be able to click on a given week and view or update lunch details for that week. We can add a click handler to each of the rows, and route the user to a new "Lunch Menu Admin Details" component.

Each lunchWeek object has a lunchWeekId property (1, 2, 3, etc). We can use this property to build a route convention that makes hierarchical sense, e.g.:

  • /admin/manage-menus --> route to the LunchMenuAdmin.svelte component

  • /admin/manage-menus/week-details/1 --> route to a new LunchMenuAdminDetails.svelte component were we can view/update the details for the lunchWeek entity where lunchWeekId = 1.

Let's stub out a new LunchMenuAdminDetails.svelte file:

 

This page is a preview of Fullstack Svelte

Start a new discussion. All notification go to the author.