Persist a New Blog
Learn how to persist a new blog in your web application and solve an issue in the success/error message.
We'll cover the following
Persist a new blog post
To start this work, open the
services/web/src/components/new-blog-post.svelte
component.
We need to define the Publish button click handler within the <script>
tag:
const publish = () => {
console.log(`Publishing...
Title: ${title}
Content: ${content}`);
};
Add the on:click={publish}
directive to the Publish button inside the <form>
tag as form’s attribute.
To make the on:click
handler work, we need to expose it in our
services/web/src/components/ui-elements/button.svelte
component. Simply add on:click
to the HTML button element. Without defining a value, it will bubble up to the parent component.
If you fill out the new blog post form now and click “Publish”, you see a message in the browser console. This is good, but what we really want is to persist that data in Firestore.
Back in the new-blog-post.svelte
component, we can update the publish click
handler as follows:
const publish = () => {
const slug = title.replace(/\s/g, "-").toLowerCase();
window.db.collection("posts").doc(slug).set({
title,
content
}).then(() => {
console.log("Success");
}).catch((error) => {
console.error("Error", error);
});
};
Get hands-on with 1400+ tech skills courses.