Write Data
Learn how to add functionalities to the components to write data to the database.
We'll cover the following
In this lesson, we are going to add functionality to the <NewBlogPost />
component at services/web/src/components/new-blog-post.svelte
. The requirements we want to meet are:
- Disable the Publish button until a title and content are available. (We did this in the previous lesson).
- Show an error message when either the title or content is empty.
- Show a success message when a new blog post is persisted in the database and empty the form fields.
We are going to tackle these requirements in the order we defined them.
Show an error message for empty fields
Click Run and open the services/web/src/components/ui-elements/input-group.svelte
component. In the <script>
tag, define new props and save it.
export let errorMessage;
export let hasError;
Add the following code below the if-else-statement (i.e. after {/if}
) to render the elementType
:
{#if hasError}
<div class="absolute inset-y-0 right-0 pr-3 flex items-center pointer-events-none">
<svg class="h-5 w-5 text-red-500" fill="currentColor" viewBox="0 0 20 20">
<path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clip-rule="evenodd" />
</svg>
</div>
{/if}
At the end of the file, add the following code to display an error message when necessary:
{#if hasError}
<p class="mt-2 text-sm text-red-600">{errorMessage}</p>
{/if}
Get hands-on with 1400+ tech skills courses.