Implement Add Transaction and Add Category Pages in Tabunganku
This is how I implement 'Add Transaction' and 'Add Category' pages in Tabunganku using Sveltekit and other various libraries
2023-07-20 · 6 min · Willy Setiawan
I designed both the Add Transaction and Add Category pages to be similar. Both pages utilize the form tag. Inside the form element, I created two columns to separate the label and the input fields.
In Svelte, the directory represents the URL. For example, if a website has a page /foo/bar, we need to create a new directory in Svelte src/routes/foo/bar and create a +page.svelte and any other files needed.
In this project, the URL to add transaction and add category is /categories/add and /transactions/add. So, we need to create new directories categories/add and transactions/add.
After that, we need to create a +page.svelte in each directory to define the page layout. +page.server.js and categories.scss are not mandatory for every page, but we use it to enhance the experience. +page.server.js is a file that contains code that will be executed by the frontend server, while categories.scss is a Sassy CSS file.
This is the code to store the category list into categories variable. Where to get the category list data ? I will get back to it later.
The rest of the code is a code to import SCSS file and the HTML layout of the page. The form action in the code above redirects to ?/addTransaction. It means the form will call a Svelte’s form action named addTransaction. Form action is a feature in Svelte to intercept the default handler with its own handler. It is implemented in +page.server.js.
load is a function that is executed by Svelte before the page loads. In this code snippet, it will get a list of categories from the backend server and return the result to +page.svelte. Remember this code snippet ?
const { categories } = data;
The result of load function is exported to the code above.
What about the ${process.env.HOST_URL} and ${process.env.USER_ID} values ? process.env is a syntax to retrieve configuration data from .env file, where I store the HOST_URL and USER_ID variables. In short, I use values stored in .env file to construct a URL.
This is the code to export actions. The addTransaction function defines /?addTransaction action in Add Transaction form. addTransaction function sends an HTTP request to the backend server to add a new transaction and log both the request and the result.
The layout of Add Category page is similar to Add Transaction page. It has an input for name, dropdown for type of category, and a color picker for category color.
Similar to Add Transaction page, there is a form action that handles a form action, which is addCategory. It creates an HTTP request to add a new category to the backend server. Unlike Add Transaction page, there is no load function implemented.