Akhil

Akhil

Build an API explorer in Svelte

Build an API explorer in Svelte

Building a simple form in Svelte

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

REPL: svelte.dev/repl/f867c81cc07a4f8db19edd2efb7..

In this article, we are going to build a simple form in Svelte which takes an API URL, makes a GET request, and shows the formatted result. The working example can be found on the above REPL.

STEP 1: create a bare minimum form

<script>
  let url = ''
</script>

<form>
    <input type="text" bind:value={url} />
    <button type='submit'>
        GET
    </button>
</form>

<input type="text" bind:value={url} /> is an input of text type. bind:value={url} is using bind directive of Svelte.

bind for two-way data binding in Svelte:

In React or any other library, in order to keep url in sync with the input value, we would have added an onChange or on:input we would have updated url with event.target.value. This sounds good if there are only a few input fields but as the number of input fields grow, it becomes repetitive and the code becomes dirty.

That's why Svelte came up with bind which keeps the value in sync providing a two-way data binding.

STEP 2: invoke function to call the API on form submission

<script>
    let url = ''
    let data

    async function getRequest(){
        if(url.length > 0){
            const response = await fetch(url)
            const parsedResponse = await response.json()
            data = parsedResponse
        } else {
            alert('Please enter a valid URL.')
            return;
        }
    }

</script>

<form on:submit|preventDefault={getRequest}>
    <input type="text" bind:value={url} />
    <button type='submit'>
        GET
    </button>
</form>

form on:submit|preventDefault={getRequest} is again a sugar provided by Svelte. | with preventDefault is an event modifier. It calls event.preventDefault() before calling getRequest method. getRequest method is a regular JavaScript method which uses fetch to make the GET request and then stores the parsed response in data.

STEP 3: showing the response data in UI

<pre>
     {#if data}
        {JSON.stringify(data, null, 4)}
    {:else}
        No data available. Please make a request.
    {/if}
</pre>

We have used <pre> tag to preserve and print the newlines and spaces that the JSON data contains. {#if data} is using yet another Svelte directive. It is an if statement in Svelte. If the data is set, it prints that using JSON.stringify(data, null, 4).

JSON.stringify(data, null, 4):

JSON.stringify(value, replacer, space) is the actual signature of stringify. If we would have just written data in the <pre> tag, it would have been shown as [object]. If we would have just used JSON.stringify(data), it would have printed everything on a single row. We wanted our data that is in JSON form to look prettified, we gave 4 as the third parameter to stringify.

STEP 4: polishing the UI:

<style>
    .form {
        display: flex;
        flex-direction: column;
        align-items: flex-end;
    }
    input.url-input {
        width: 100%;
        min-height: 3rem;
        border-radius: 8px;
        border: 1px solid;
        font-size: 1.2rem;
    }
    input:focus {
        outline: none;
        box-shadow: 0px 0px 1px 2px rgba(104,87,250,0.2);
    }
    button {
        width: 50%;
        background: #457bf7;
        color: #fff;
        padding: 0.8rem;
        border-radius: 8px;
    }
    pre {
    background: #f6fafd;
    padding: 0.5rem 1rem;
    border-radius: 8px;
    }
</style>

<style> is used to add CSS in Svelte components. <style> automatically scopes the CSS to the component.

That is it...

Live App

Please like, share & comment if you think it helped in getting to know about forms in Svelte. Thanks for reading.

Interested in reading more such articles from Akhil Gautam?

Support the author by donating an amount of your choice.

Recent sponsors
 
Share this
Proudly part of