Svelte State Management: Creating Contact Form

Written by the_rock | Published 2020/02/01
Tech Story Tags: svelte | javascript | state-management | web-components | typescript | nodejs | programming | beginners

TLDR In this tutorial, we are going to see how to create a mutable state by using a writable object. The project is going to be a simple page where you can add contacts into a list of contacts. We will use a store object, subscribe to it, add new entries and reset its value. This component will show all contacts and update automatically, but it’s better to use $ as prefix to contacts. In this way, Svelte will manage subscription automatically.via the TL;DR App

Recently, I came into Svelte and ... I love it.
Hi rocks, Sasha here. Today we are going to do some state management in Svelte.
There are different ways of managing state in Svelte. In this tutorial, we are going to see how to create a mutable state by using a writable object.
The project is going to be a simple page where you can add contacts into a list.
So, let’s start by creating a svelte project: open your terminal, go to the target folder you want to create project in and run:
npx svelte3-app
Once it’s done, you can start a project by running:
npm run dev
It will deploy your app on
localhost:5000
and enable hot-reload.

Store

Let’s create our store object under src/store and call it
contacts[.js]
.
In there, we are going to define a default value for our store, create a store and expose addContact and reset methods.
import { writable } from 'svelte/store';

//value used as default for the current store
const DEFAULT_CONTACTS = [
    { name: "John", surname: "Doe", mail: "john.doe@mail.com" },
    { name: "Alice", surname: "Wonderland", mail: "alice.wonderland@mail.com" }
];

// create a store
// subscribe    -> must be exported, will discuss it in future article
// set          -> allows you to set a value to store
// update       -> receives a current store value as input and returns a new one.
const { subscribe, set, update } = writable(DEFAULT_CONTACTS);

//receives a new contact in input and updates current stored value by pushing a new one
const addContact = contact => update(contacts => {
    //we're returning a new array in order to achieve reactivity
    return [...contacts, contact];
});

// sets a default value to store
const reset = () => {
    set(DEFAULT_CONTACTS);
};

//public methods
export default {
    subscribe,
    addContact,
    reset
}
So, now we can import our contacts store into components, subscribe to it, add new entries and reset its value.

Components

We are going to create two components:
ContactForm
, for inserting new contacts, and
ContactsList
, for showing the list of stored contacts.

ContactsList

<script>
	import contacts from "./store/contacts";
</script>

<div id="contactsList">
	{ #each $contacts as contact }
		<p>{contact.name} {contact.surname}</p>
		<p>{contact.mail}</p>
		<hr />
	{ /each }
</div>
This component will show all contacts and update automatically. You can explicitly subscribe to store, but it’s better to use $ as prefix to contacts. In this way, Svelte will manage subscription automatically.

ContactsForm

<script>
	import contacts from "./store/contacts";

	// binding values
	let name = "";
	let surname = "";
	let mail = "";

	// submit contact
	const submitContact = () => {
		contacts.addContact({ name, surname, mail });
		// reset values
		name = surname = mail = "";
	}
</script>

<div id="contactForm">
	<input type="text" 	bind:value={name} placeholder="Insert name" />
	<input type="text" 	bind:value={surname} placeholder="Insert surname" />
	<input type="email" bind:value={mail} placeholder="Insert mail" />
	<input type="submit" on:click={submitContact} value="Add" />
	<input type="submit" on:click={contacts.reset} value="Reset" />
</div>
This component simply binds values and triggers submitContact on Add button press.

App

Now, you can import both components to App and let the magic happen.
<script>
	import ContactsList from "./ContactsList.svelte";
	import ContactForm from "./ContactForm.svelte";
</script>

<main>
	<h1>State managment!</h1>
	<ContactForm />
	<ContactsList />
</main>

Written by the_rock | Software Developer from monday to friday (Healthcare sector), Game Developer in free time
Published by HackerNoon on 2020/02/01