Svelte – each block – grouping and saving data

Example of work bind: value based each block.

Code below:
– generates a table through each from data that comes from the backend;
– saves entered data from input and sends them to back.

In this code, the implementation of only the front, demonstrates the work svelte… What happens on the backend is not important here and is provided for illustration.

1. JS block

There is an important point here. We definitely need to add the received data through onMount… Otherwise svelte won’t work with bind, when we need to save the data in the manner shown below.

We get data from the backend:

import {onMount} from “svelte”;
import {getFetchOther} from ‘../../main’;

let settings = [];
onMount(async () => {
getFetch(‘settings / get-user-timers /’)then((r) => {settings = r});

Save function, which will be triggered automatically each time data is entered into the input:

function changeValue(setting) {
getFetchOther(‘settings / save_user_timer /’ + + ‘/’ + setting.timer + ‘/’ + setting.percent);

2. Svelte block

This is where the table is output from the data in a variable settings

Design on: change = {changeValue (setting)}, when the content changes, input sends data to the function changeValue (higher). It, in turn, sends the data to be saved to the backend.

<div class=“table table-links”>
<div class=“header”>
<div class=“cell title name”>Name</div>
<div class=“cell title timer”>Timer (in minutes)</div>
<div class=“cell title percent”>Coefficient in%</div>
<div class=“body”>
{#each settings as setting, i}
<div class=“item”>
<div class=“cell name”>{}</div>
<div class=“cell timer”>
<input type=“text” bind:value=“{setting.timer}” on: change={changeValue(setting)}>
<div class=“cell percent”>
<input type=“text” bind:value=“{setting.percent}” on: change={changeValue(setting)}>
{/ each}

Similar Posts

Leave a Reply