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
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:
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.
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
/admin/manage-menus/week-details/1--> route to a new
LunchMenuAdminDetails.sveltecomponent were we can view/update the details for the
lunchWeekId = 1.
Let's stub out a new