Welcome folks today in this blog post we will be building a svelte user crud app
in browser using javascript. All the full source code of the application will be given below.
Get Started
In order to get started we will be using the degit
tool to create a basic svelte app as shown below
First of all we will be installing degit
globally inside the machine using the below command
npm i -g degit
And then you need to initialize a new svelte
project using the below command
degit sveltejs/template crudapp
cd crudapp
Directory Structure of Svelte App
After you create the svelte app you will see the directory structure of svelte app which is shown below
Now we will be modifying the App.svelte
file inside the src directory as shown above of svelte project.
src/App.svelte
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<script> // javascript code goes here </script> <section> // html code here </section> <style> // css code here </style> |
As you can see this is the basic structure of every Svelte Component. We have three sections out there which is the html, css and javascript. It is looking similar to Vue.js and React.js App.
Now guys we will be declaring the users array for our svelte app. Inside this user object we will be having three properties name, age and country as shown below. As you can see we have also have the id parameter which is given to each record and it’s unique because we will be using this property to perform the crud operations later on.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<script> let users = [ { id: 0, name: 'John Williamson', age: 26, country: 'New Zealand' }, { id: 1, name: 'Kane Williamson', age: 31, country: 'New Zealand' } ]; </script> |
Displaying Users in HTML Using Loops
Now guys we will be looping through all the records which are present inside the users array. For looping we will be using the each block which is shown below
1 2 3 4 5 6 7 8 |
<section> {#each users as user} <div>{user.name} is {user.age} years old and lives in {user.country} </div> {/each} </section> |
As you can see we are looping all the records which are present inside the users array. And here you can see we are using the {#each} {/each} block inside this we are passing the users array and then we are using the local variable user which is used to print out the actual details which is name, age and country. If you now run your svelte app inside the browser it will look something like this
Running Svelte App
For running the svelte App you need to run the below command
npm run dev
Creating the User Using HTML5 Form
Now we will be creating the user record using the html5 form. For creating the record we will be have to write the below code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<h5>Add New User</h5> <form> <div> <label for="name">Name</label> <input bind:value={data.name} type="text" id="text" placeholder="Enter Name" /> </div> <div> <label for="age">Age</label> <input bind:value={data.age} type="number" id="text" placeholder="Enter Age" /> </div> <div> <label for="country">Country</label> <input bind:value={data.country} type="text" id="text" placeholder="Enter Country" /> </div> <button type="submit" on:click|preventDefault={addUser}> Add User </button> </form> |
As you can see we have the html5 form above. Inside the form we have three fields which is taking the input for name,age and country. And then we have the button to create or add the user. Before this you need to declare an empty object of data which will contains all the properties name,age,country and id as shown below
1 2 3 4 5 6 |
let data = { name: '', age: '', country: '', id:null }; |
As you can see we have set the id to null here.
And also inside each input field we are attaching a two way binding using the bind:value selector. It has various advantages basically this means whether the name,age or country changes using this input field then that value present inside the array will automatically change. And also to the button we are also attaching onClick event listener. When we click the add User button we are executing the custom function which is addUser function.
Adding New User Using Concat() Method of Arrays
Now we will be adding a new User inside the users array using the concat() method of arrays. So here we are writing the addUser() method when we click the button
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
let addUser = () => { const newUser = { id: Date.now() + Math.random(), name: data.name, age: data.age, country: data.country }; users = users.concat(newUser); data = { name: '', age: '', country: '', id:null }; console.log(users); }; |
As you can see we have the arrow function inside that we are creating a new user object inside that we are providing a unique id using Date.now() and Math.random() methods. And also we are getting the name,age and country using the data object that we declared earlier on. We have binded the properties of data object on the input fields. Using the two way data binding we are getting the values which the user has typed and storing inside this object. And then we are using the concat() method and this method returns a new array and stores it inside the users array. And lastly to reset the input fields in the form we are again initializing name,age and country,id to empty and null values.
And now if you open the svelte
app inside the browser the output will look like this as shown below
Deleting the User Using it’s ID
Now we will be performing the delete operation of a particular user using it’s id. Where we are displaying the list of users using the each block we will be adding a delete button for every user. So that when you click the delete button of a particular user then that id is passed of that particular user will be passed an argument to the delete function as shown below
1 2 3 4 5 |
{#each users as user} <div>{user.name} is {user.age} years old and lives in {user.country} <button on:click={deleteUser(user.id)}>Delete</button> </div> {/each} |
As you can see we have the on:click event listener on the delete button and here we are passing the id parameter of the user. So when the delete button is clicked we are deleting the user from the array.
1 2 3 4 |
let deleteUser = (id) => { console.log(id); users = users.filter((user) => user.id !== id); }; |
As you can see we are deleting the user by using it’s id. Here in the delete function we are using the filter function where we are comparing the user id to each and every user id. If the id of the user matches and then we will not be including that user in the array thereby eliminating or deleting that user from the array.
Updating an Existing User Using it’s ID
Now we will be modifying the properties of the existing user using the findIndex() method of the array. So for this purpose also we will be using the id parameter for updating the existing user. So again we will add the second button of update where we are looping all the users and displaying it as shown below
1 2 3 4 5 6 7 |
{#each users as user} <div>{user.name} is {user.age} years old and lives in {user.country} <button on:click={editUser(user)}>Edit</button> <button on:click={deleteUser(user.id)}>Delete</button> </div> {/each} |
This time as you can see we have the second button of Edit User when you click this button the function editUser() will execute and here we are passing the entire object of that particular user. All the properties which are present will be there inside this editUser function.
1 2 3 4 5 |
let isEdit = false; let editUser = (user) => { isEdit = true; data = user; }; |
As you can see we are declaring one boolean variable at the top of this function which is onEdit which is set to false when we load the application for the very first time. And when we click the edit button we are changing this boolean variable value from false to true. Thereby enabling to change the label of the button from createUser to UpdateUser as shown below. And also we are initializing the data object to the passed user.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<form> <div> <label for="name">Name</label> <input bind:value={data.name} type="text" id="text" placeholder="Enter Name" /> </div> <div> <label for="age">Age</label> <input bind:value={data.age} type="number" id="text" placeholder="Enter Age" /> </div> <div> <label for="country">Country</label> <input bind:value={data.country} type="text" id="text" placeholder="Enter Country" /> </div> {#if isEdit === false} <button type="submit" on:click|preventDefault={addUser}> Add User </button> {:else} <button type="submit" on:click|preventDefault={updateUser}> Edit User </button> {/if} </form> |
As you can see we are using a conditional of If inside the html and here we are using the isEdit value here. If it is equal to false then we are showing the createUser Button. If it is equal to true then we are showing a different button whose label is Update User. As you can see we have attached a onClick Event listener to the updateButton. When we click this update button we are executing the UpdateUser method. Now we need to write this method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
let updateUser = () => { isEdit = !isEdit; let userDB = { name: data.name, age: data.age, country: data.country, id: data.id }; let objIndex = users.findIndex((obj) => obj.id == userDB.id); users[objIndex] = userDB; data = { id: null, name: '', age: '', country: '' }; }; |
As you can see we are defining the updateUser function which is an arrow function inside this function we are first of all toggling the value of the boolean parameter isEdit. And then we are creating a new User object and we are taking the values of all the properties from the data object. And then we are finding the index number of the record we need to update the details. For this purpose we are using the findIndex() method and inside it we are receiving an object and we are checking the id of the user is equal to the passed id of the defined user. If both the id are equal then we will stop the loop and get the index number. After that we are updating that particular user values. And lastly we are once again resetting the values of the data object.
Full Source Code
App.svelte
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
<script> let users = [ { id: 0, name: 'John Williamson', age: 26, country: 'New Zealand' }, { id: 1, name: 'Kane Williamson', age: 31, country: 'New Zealand' } ]; let data = { name: '', age: '', country: '', id:null }; let addUser = () => { const newUser = { id: Date.now() + Math.random(), name: data.name, age: data.age, country: data.country }; users = users.concat(newUser); data = { name: '', age: '', country: '', id:null }; console.log(users); }; let isEdit = false; let editUser = (user) => { isEdit = true; data = user; }; let updateUser = () => { isEdit = !isEdit; let userDB = { name: data.name, age: data.age, country: data.country, id: data.id }; let objIndex = users.findIndex((obj) => obj.id == userDB.id); users[objIndex] = userDB; data = { id: null, name: '', age: '', country: '' }; }; let deleteUser = (id) => { console.log(id); users = users.filter((user) => user.id !== id); }; </script> <section> <h5>Add New User</h5> <form> <div> <label for="name">Name</label> <input bind:value={data.name} type="text" id="text" placeholder="Enter Name" /> </div> <div> <label for="age">Age</label> <input bind:value={data.age} type="number" id="text" placeholder="Enter Age" /> </div> <div> <label for="country">Country</label> <input bind:value={data.country} type="text" id="text" placeholder="Enter Country" /> </div> {#if isEdit === false} <button type="submit" on:click|preventDefault={addUser}> Add User </button> {:else} <button type="submit" on:click|preventDefault={updateUser}> Edit User </button> {/if} </form> {#each users as user} <div>{user.name} is {user.age} years old and lives in {user.country} <button on:click={editUser(user)}>Edit</button> <button on:click={deleteUser(user.id)}>Delete</button> </div> {/each} </section> <style> </style> |