Member-only story

Handle Svelte Forms Easily With Actions

Mark Caggiano
4 min readSep 14, 2022

--

Creating forms can be boring… usually in Svelte JS and in general with other frameworks, you have to create the data, process it, validate it, send it, handle the response and also write down the html markup.

<script>
const data = {
user: '',
pass: '',
}

const handleSubmit = (e) => {
axios.post('endpoint', data)
.then(res => {
console.log('Everything went good: ', res.data)
})
.catch(err => {
console.log('Something went wrong: ', err)
})
}
</script>

<form on:submit|preventDefault={handleSubmit}>
<input type="text" name="user" id="user" placeholder="Username">
<br>
<input type="password" name="password" id="password" placeholder="Password">
<br>
<button type="submit">
Login
</button>
</form>

For a simple form like this is pretty easy using standard stuf, but what if we want to handle more complex form with 10 or 20 elements and validation ?

Things becomes crazy, but there is a better way of handling this.

We can use SvelteJS Actions

Actions are basically functions you attach to a DOM Element, and from where you have access to the element and you can do everything you want using svelte and vanilla js.

--

--

Mark Caggiano
Mark Caggiano

Written by Mark Caggiano

Internet Marketer, Web Developer, Traveler

No responses yet