Syntax Video
Full Stack App Build | Travel Log w/ Nuxt, Vue, Better Auth, Drizzle, Tailwind, DaisyUI, MapLibre
- 0:00 intro / overview
- 7:27 stack / architecture overview
- 12:18 github project board setup
- 15:50 project setup
- 17:52 github auto deploy with vercel
- 19:21 eslint / editor setup
- 21:10 antfu eslint-config
- 25:57 pre-commit hooks lint
- 30:30 git feature branch worflow
- 32:12 lint github action
- 38:48 tailwind setup
- 41:25 daisy ui setup
- 44:38 nuxt/icon setup
- 49:25 landing page
- 57:44 theme toggle / color mode
- 1:05:14 typesafe env with zod
- 1:11:54 db setup
- 1:13:21 drizzle setup
- 1:18:00 turso local development
- 1:22:25 db schema
- 1:29:42 set environment variables on vercel and github actions
- 1:31:46 auth setup with better-auth
- 1:40:00 github oauth setup
- 1:47:56 create auth store with pinia
- 1:52:31 auth error page
- 1:56:31 github oauth production configuration
- 1:58:08 turso cloud setup
- 1:58:53 run db migrations on production
- 2:01:24 auth status display
- 2:08:02 sign out page
- 2:12:48 protected routes redirect
- 2:16:25 SSR Auth Session
- 2:25:41 create dashboard sidebar
- 2:36:38 collapsible sidebar
- 2:47:16 persist sidebar collapse in localStorage
- 2:50:05 dashboard nested routes
- 2:52:05 create location form
- 2:57:20 validate form with vee-validate
- 2:58:53 drizzle zod validation schema
- 3:03:35 handle location form submit / show validation errors
- 3:07:59 re-factor form field component
- 3:14:53 show confirmation if unsaved changes in form
- 3:18:01 create location API route
- 3:19:21 validate location before insert
- 3:21:14 display server errors on form
- 3:30:06 loading state during create location
- 3:33:11 insert location into db
- 3:34:19 access logged in user in API route
- 3:37:59 insert location into db with userId
- 3:39:08 redirect after creating new location
- 3:41:12 csrf protection
- 3:46:54 validate unique location slug and name
- 3:50:22 generating slug during location insert
- 3:57:19 unique location name per user database constraint
- 3:59:35 oops - reset entire db / migrations
- 4:01:41 show unique location name error
- 4:04:10 consolidate location table db queries
- 4:12:23 show form errors in production
- 4:13:29 list locations in dashboard
- 4:16:41 create authenticated event handler util
- 4:22:46 list locations API route
- 4:24:17 list locations in dashboard
- 4:34:21 list locations in sidebar
- 4:52:06 map setup
- 4:54:50 set up nuxt-maplibre
- 4:59:39 map styles setup
- 5:05:55 list locations on map
- 5:17:09 center map on location bounds
- 5:29:53 map popups
- 5:32:48 override maplibre popup styles
- 5:37:20 set selected location on hover
- 5:48:22 zoom to map point on hover
- 5:56:27 drag marker to set location coordinates
- 6:10:15 center map on draggable marker
- 6:15:15 double click map to set location
- 6:20:30 places search api options
- 6:24:25 place search
- 6:25:31 view location page
- 6:29:59 typecheck npm script
- 6:31:45 view location page continued
- 6:41:25 location logs relation / query
- 6:46:59 view location by map marker
- 6:59:19 location specific sidebar links
- 7:05:17 refactor current location into store
- 7:11:54 location specific sidebar continued
- 7:19:20 update location details form
- 7:36:17 fix current location SSR
- 7:39:11 update location details form continued
- 7:42:39 fixing data loading issues
- 7:47:31 update location details form continued
- 7:48:46 update location details api
- 8:02:28 delete locations
- 8:12:45 delete location api
- 8:18:35 create location log form
- 8:47:38 create location log api
- 8:55:03 list location logs
- 9:08:03 list location logs in sidebar and on map
- 9:16:49 view location log
- 9:30:29 edit location log
- 9:41:45 delete location log
- 9:48:19 minio local s3 storage setup
- 10:00:52 s3 image upload flows
- 10:04:38 select upload image
- 10:12:07 resize / optimize image on client
- 10:17:20 create image checksum on client
- 10:19:23 create pre-signed post url on server
- 10:32:25 get pre-signed post url on client
- 10:38:40 upload image to s3 from client
- 10:41:59 insert image metadata into db
- 10:52:54 list images
- 11:08:14 s3 production setup
- 11:14:59 delete images
- 11:25:33 final fixes
- 11:35:19 nuxt sentry setup
- 11:39:41 final deployment
- 11:40:30 thanks!
intro / overview
Welcome to this build series where we'll be building an application that allows users to keep track of all the places that they've visited. Now, in this video, we're going to be building it with Nux. But if you somehow clicked on this video and you're not interested in Nux, please leave a comment down below because I will be building this app with other meta frameworks like Tanstack Start or Nex.js or Solid or SpeltKit.
So, if you're interested in seeing this app built in any of those other frameworks, let me know down in the comments. But this video is all about Next. Now, like I said, the app that we're building allows users to keep track of all the locations that they've visited. So, you can see here on the map, we have all these top level locations. And then for any location, we can dial in to a nested route. And these are all the specific times that I visited that location. In this example, I'm just keeping track of all the live shows that I went to in Denver last year. But you can see now that I've dialed in, we have these shows. They're on the map. I can then dial in further and we can view all the images that I uploaded for this specific location log.
Everything you see in the app is credible or create, read, update, deletable. So for any given location, I can update its details. For any specific log, I can update its details. Every single form in the app has client side validation as well as server side validation. And we pay attention to the little things. So if a user starts changing the data for a form and they try to go back, we let them know, hey, you might lose your progress. Now, there's lots of other bits of nice user experience things that we have in here.
So for instance, if I want to add another location to the map, let's say we add Washington DC. Whenever we search, we show that loading spinner. We let the user know that something's happening. And there's lots of nice map interactions here. So if I choose a location, it'll pan over and zoom to that location. Because we're using Nux, when we're using this app, we kind of have a hybrid approach. So the initial page load when you visit the website is serverside rendered but then as you start to navigate around this actually uses client side rendering and behaves more as a single page application. So I highly recommend go try the app out. If you visit nux-travel-log.verell.app you can click around you can sign up. You can try adding things and you'll notice things are fairly zippy. Of course we do have loading spinners because we're talking to a database. is like network latency, but I've made sure that all of the actions that a user is performing when you're working throughout the app just feel good and the user knows that things are happening. It doesn't feel like the pages are just freezing or anything like that. And you'll also notice that there's a lot of shared data in this application as well, right? When we're on the main dashboard here, we have all
of the cards listed out at the top. When I hover over them, they're actually highlighted on the map. We also have these items in the sidebar. And when I hover over on the map, they highlight in the sidebar and in the cards. So, we're using global shared state throughout our application that allows all of these pieces to stay in sync. So, no matter which one I dial into, all of that state is shared and can be accessible from either the map or the cards or the sidebar. Now, as you've seen as I've navigated through this app, there's actually multiple levels of nested routing. Pay attention to the URL here.
If we dive into San Francisco, we can see it's locations/lug. If we dive into a specific time that I visited San Francisco, it's location slug ID. And then each of these has a unique set of links in the sidebar so that the user can perform actions in context where they're actually at. And to get a highle view of all of that, this is kind of the page flow. You have your not logged in users, your loggedin users, your overall dashboard with locations. We can add locations. We can then visit specific locations. We can update the details for a specific location. We can log each time we've visited that location. We can view individual logs. is we can view the images, edit logs, and then we can also manage all of our images as well. Now, this is a really big app with lots of features and lots of things that we worked on. So, for this, I've actually created an entire set of GitHub issues and a project board. So, if you decide to build this app, I have a tool that will get this up and going for you.
Essentially, it creates every single one of these stories that we'll be working on. And then for each one, it has lots of details about how to implement that story. For example, in the database setup, we have the database schema here that you can use to implement your database schema, as well as a checklist of all the things that you'll need. And for some of these stories, I also include useful screenshots that'll help you whenever you're setting up all this stuff. So, even if you don't follow this tutorial, you could set off to build this app yourself. And I've broken it down into all these features and everything you'll need to get up and going to build this full stack travel log application. Now, as you can see from the runtime of this video, we cover a whole lot. Now, if you don't want to follow this video from beginning to end, there's lots of little tidbits of information throughout. So, definitely check the timestamps in the description.
The first section of this video is all about setting up our Nux app. So, if that interests you, you can check out that portion. We also set up GitHub actions and automatic deployment with Versell. So, if that interests you, check out that section. From there, we set up Drizzle OM. We also have authentication using better off. So I show how to configure better off within a Nux application. We're using Daisy UI for all of our UI components. So I show how to get set up and going with that.
And we also have light mode and dark mode. I didn't show that when we were demoing the app. So you can see here I toggled to light mode. And the map styles actually swap out to light mode whenever we swap between light mode and dark mode as well. Now another aspect of this build is we talk a lot about reusability and refactoring. So you can probably notice throughout the application there's several spots that could potentially be a reusable component. And the way that we build this is to first kind of get it working and then take a step back and think about well where can this be reused throughout our application. So there are multiple spots in this video where we go through a refactor of consolidating code and making things much more maintainable. Now if you're looking for the cure to YouTube tutorial hell, this is definitely it. You could of course follow this video from beginning to end, but I provide a ton of opportunities for you to go off and try to build things on your own and things are set up in a way to where you could try to build them before watching me build them. So, if you've been stuck just watching videos and not actually building, this is definitely the course for you. Another
aspect of this course is I don't use any AI while I'm building it. Now, AI is absolutely useful and I do use it in my personal work, but if you're learning all of these things for the first time, being really hands-on with all this stuff instead of just having AI generate the code for you is a really great way to learn it and get a really good grasp on it before you start using AI to make you work a little bit faster. Now, like I mentioned, we're building this app with Nu.js. If you are completely new to Nux.js, check out the crash course that I released on the syntax channel here that gives you a general overview of how to work within Nux.js. And if you're completely new to Vue.js, which Nux.js uses under the hood, I also have a Vue.js crash course you can check out there. So this video assumes beginner to intermediate level knowledge of Nux and Vue. I still explain absolutely everything as we go, but sometimes I move a little bit fast, so there will be areas of this build where you'll have an easier time if you've had a little more practice with this stuff and this isn't the first time that you're seeing it.
Now, lastly, if you're following this course and you have a question or maybe a a more in-depth code question that doesn't work in the YouTube comments, join the syntax discord. There'll be a link in the description and ask your question in there. I'll be in there every now and then answering questions and then also people from the community will be answering questions as well. So, if all of this sounds good to you, let's dive in. My name is CJ. Welcome to Syntax. Now, let's talk about the stack.
stack / architecture overview
Of course, we're using Nux.js, which is built on top of Vue.js. So we'll be spending the majority of our time working on Vue components, but of course we're using several external libraries. For the front end, we'll be using Tailwind CSS and Daisy UI. So Daisy is a UI component library built on top of Tailwind that gives you a ton of default UI components out of the box, so you don't have to fumble around with Tailwind classes, but if you need to add some custom styles with Tailwind, you can. And they also have a full theming system, so we'll be enabling dark mode and light mode in our app as well. We'll also be using Iconify on the front end.
So all of our buttons will have nice icons to indicate to the user what they actually do. And throughout the app, because we have multiple levels of routing and lots of pages, we will be using PIA, which is the global state management solution in the Vue.js ecosystem. So we'll have several PIA stores that allow us to share data throughout our application. For the map portion of the application, we're going to be using an open source library called map libre. It's completely free to use, no usage tokens or anything like that. And for our tile server, we'll also be using a completely free tile server called open free map. Our app is also going to allow users to search for points of interest on the map. And for that, we're going to be using the nomen atm search API which comes from open street map. And all of the search results we get back there will be caching using unsto. For form validation, we'll be using a library called validate and we'll pair that with zod. So we'll have ZOD schemas for every single thing that we'll be sending to our API and that will also be validated on the front end before it even makes it to the back end using Validate and Zod.
For our database and OM we'll be using Drizzle OM which is the best TypeScript OM and we'll be talking to a lib SQL database which is SQLite. Now we'll pair that with Drizzle Zod which gives us Zod schemas for all of the tables that we defined where the single source of truth is that TypeScript definition for our table and then those Zod schemas can be shared and used by all of our forms for validation. So we have full type safety here with a single source of truth. So all of our validations on the front end are the exact same validations that are happening on the back end as well. Now next is built on top of a framework called Nitro which in turn is built on top of a runtime agnostic API framework called H3. So the file-based routing throughout the application and also all of our API routes are going to be defined using Nitro and H3 functions.
For authentication we're going to be using better off with GitHub. Better comes with a Nux integration that works well. They provide a client side and a serverside library. And all of the routes throughout our application are going to be locked down so that only logged in users can perform actions. And when a user is retrieving data, they only can retrieve data that they specifically have access to. Users will be able to upload images inside of our app. And for that, we're going to be using S3 compatible storage. And then lastly, to make sure that we have a really nice clean codebase, we're going to be using ESLint combined with Husky pre-commit hooks and also lint staged.
And every PR we make to our git repo is going to run through a GitHub action to run all of our lint tasks to make sure our code is in a good state before it gets merged in. And from there, any merged code automatically will be deployed using Verscell. Now, one of the aspects of this architecture and how we're going to be deploying and working locally is that we're not locked in to any service or thirdparty provider. You might have seen a lot of tutorials out there that are using hosted O services or specific kinds of like hosted databases. Our app can run entirely locally on our machine and we can actually change where our database is hosted, where our images are hosted, where we're deploying to. We're using Verscell like I said, but Nux actually supports lots of different deployment providers. So, we could change all of that as well. So, this is one thing that I really harp on when we're building this application is too much dependency on thirdparty services can make it really hard to work on a larger team to be able to share those resources. So, being able to have everything run locally and every developer on your team being able to run that stack locally is a huge win. So specifically for our SQLite database, when we're running
locally, we'll be using Terso dev. This just spins up a local Terso server. So I can talk to a local SQLite database. And then when we're running in production, we'll be using Terso cloud. For the app itself, when we're running locally, we're using the V dev server. And then when we deploy, it'll be running on Verso. Like I said, NX supports a lot of different hosting providers. So we could swap that out if we wanted to. For S3 compatible storage, we're going to be using an open source project called Min.io when we're running locally. So this just runs inside of a Docker container. It has an S3 compatible API.
So our app actually uses the AWS S3 SDK, but we just point it to Min.io when we're running locally. And then whenever we deploy, we actually point to an AWS S3 bucket in the cloud. And then for our UNS storage caching, this is just using the local file system module, but unsto also supports a lot of different key value storage providers like Reddus or Upstash. So we don't actually set that up in this tutorial, but because Nux is using Nitro, which is using Unsto, you actually can swap this out for any key value provider. So this is our architecture. This is what we're going to be using. But throughout this tutorial, anytime I'm choosing one of these libraries, I talk about why I chose it and also talk about what you could use instead. So most of these pieces are actually swappable. And I highly encourage that if you don't like the choices that I made when building this application, feel free to choose something else or swap it in. That's really the beauty of this architecture and all of these choices. Now, like I mentioned, every aspect of this application has been broken down into GitHub issues and a project board. So, if you're going to be following this video, you should get a project board
github project board setup
set up. And I've actually created a tool that will automatically create all of the issues and add them to a project board for you for this specific app build. So, next up, I'll show you how to run that tool and get your project board ready so you can follow along in the video. So, first we'll clone down this tool, which is going to create all of the issues and then link them to a project board. So, we'll grab the URL and then from the terminal, we can do a get clone. Then head into that directory, do a pmppm install, and then open it up with your favorite editor so we can update thev file. So you can see we have this example env file. We're just going to want to copy it and then create a new one that's just called.env.
And then inside of here, you'll specify your GitHub username and then the name of the repo where you'll be creating this project. For me, it's just NUX travel log. And then you'll need to add your GitHub token here. So from the repo, I have a link to where you can do this. It's in your GitHub settings. Once you're here, just give it a name like travel log project board creator. You can set an expiration date. It's only going to be used one time. It needs the repo permission and then it also needs the project permission. So, generate that token. Once it's generated, put it into yourv file. Now, we need to create the repo and then project board so the tool can work its magic. So, create the repo here. Be sure you give it the same name that you specified in thev file and then just create it. A blank repo for now is perfectly fine. Head over to projects and then we're going to create a project. Now, it's important that you choose the conbon board. The tool specifically is looking for the backlog column and it's specifically looking for the board layout. So, you want to choose this preset and just give it a name and
create it. So, now that we have the repo and the project board, the tool is ready to do its work. So from the command line, if you just do pnpm start, it will reach out, find the repo, create all of the necessary labels, it'll then start creating all of the issues, and then link those to the project board. Now, if this fails for some reason, I had some issues where the the GitHub GraphQL API went down for a second. And so if this fails, just rerun pm start, and it'll pick up where it left off and finish creating all of the uh labels and issues and everything else. And once the tool is done running, you should see 46 issues created here on your GitHub repo.
And then if you head to projects, you should see that project with all of those issues in the backlog column. Now, by default, they actually have a limit of five in the backlog. We're just going to set this to a th00and because the backlog is all of the things that we will potentially work on. And because we're a single person team, when we're working on something, we're just going to drag it to the inrogress column. I'm actually going to delete the ready column and the in review column. These are great if you're working on a team and maybe you have like a PM that chooses what's up next. they would put that in the N ready column. And maybe you have a QA team or maybe you have another developer that's going to review the code, you can put it into the in review column. We're working solo, so we're going to have a very simple conbon board where when we start working on something, we pull it into in progress and then once it's done and deployed, we pull it over to the done column. Now, for all of the items in the backlog, they're listed in priority order, so the order that they should be done logically in order for all the pieces to be in place. There might be a few that maybe you want to work on before others, but
for the most part, everything is kind of like in chronological order according to what needs to be set up before we work on that next feature. So, if you follow this backlog from top to bottom, you should end up with a working app. Let's get started on our first task, which is project setup and initialization. So, for each of these tasks, there are also check marks in the issues. So, as you get things done, you can check them off.
project setup
And first up, we need to initialize the project with the CLI. If you head to nux.com, they have a command that you can run. We're just going to copy this and then I'll run this command in my projects folder. Now, this will create a new folder. So, just make sure you run this in a spot where you want the project to be created. So, we're going to call this next travel log. I like to use pnpm. And then we will initialize this as a git repository. Now, this is one of the nice things about the Nux CLI. They have all of these plugins that you can just enable and automatically get like ESLint setup and image processing and all this other stuff.
We're going to skip that for now because we will cover it in some future stories. Right now, we just want a base repo. So from there I can CD into that directory. Let's go ahead and open it up with VS Code. Now if we look at our tasks, we've initialized it with the CLI. We have a git repo and by default it does have that git ignore there which is good. And it actually does come with a read me with setup instructions. But let's just update it. So because we're using PNPM, I'm going to remove all the instructions that say to use other things. Just kind of simplify it. And I'm going to give it a good name. Give it a nice description there. And then we'll update the run command. and then the build command and the local preview command. And I'm going to get rid of this because we're going to handle that ourselves. So, we have a pretty basic readme. If anybody else comes along and tries to clone our repo, they know how to get set up and get started. So, that looks good to me. Now, if we start this up, so from the command line, let's just do a ppm rundev. It should work. We have the base next app.
I'm not going to work on the landing page or anything like that because we have a separate task for that. But, our app is good to go. So from here, I'm going to commit my changes and then we'll push them up to GitHub. So now I have my initial commit. If I want to push to GitHub, I'm going to need to grab the remote. So over here on our repo. If it's still a base repo, which it should be, we can actually just grab this command here, which is going to add this as the remote and then automatically push that code up. Sweet.
If we refresh over here, we have ourselves a Next app on GitHub. All right, all of that's ready to go. Now we can set up GitHub autodeploy. Now on the Nux site, you can see all of the hosting integrations that they have. You can deploy to a bunch of different places. We're just going to use Verscell because it's what I'm used to, but if you like any of these other services, you can follow their guides for deploying there as well. So, if you head to verscell.com/new, make sure you have linked your GitHub account to Verscell, then you should see your repos listed here. I have limited scope here, so I've chose the specific projects that I want Verscell to have access to. But here's the NX travel log. I'm just going to click import. So, it detects that we're using Nex.js, and that has all of the defaults that we need. So, I'll just click deploy. All right, looks like it's deployed. We'll head to the dashboard and that should give us a link to our deploy. And if we head to it, the site works. Now, I'm the first person to create nux-tra-log. So, your URL is definitely going to be different, especially if you named it the same thing, but nux-tra-log.ver.app, that's mine. I've built some apps in the past and people
github auto deploy with vercel
got confused because they called it the same thing. Yours will likely have some numbers or letters on the end if you called it the same thing. But, we're deployed. And if we head over here to GitHub, we can see there's a check mark on that commit. And so now every time we merge into the main branch, it is going to deploy it to Verscell. So we can check that off. And it looks like we're done with this first story. So we'll drag this over to done. And one of the nice things about this project board automation is that once you drag an issue to done, it actually closes that issue. So we're ready to keep moving.
Next, let's work on our ESLint and editor setup. So for this chore, we need to set up ESLint, set up our editor settings, and then we'll also set up uh Git hooks. So locally before we commit it's going to run our llinter and then after that we'll also set up a GitHub action. So before deploying to Verscell it makes sure that all of the linting checks pass. So for our ESLint setup if you head to kn.com and click on modules you'll see that they have a bunch of official modules and also community modules and they have a built-in module called eslint that configures everything for you. So let's head over here. It'll give us a command we can run to install it. So this is the command we need.
eslint / editor setup
We're using pnpm. So instead of npx, we will have to do pnpm dlx and then the command that we want to run. Great. So that installs all of our dependencies and then also updates our nux config which we'll show you next. So if you look at the nux config, you can see that the eslint module is listed there. And if you look at our package.json, we now have a dependency on it. And this generated our default eslint config. Now you can run through their docs to see all of the customizations you can do.
And one of them actually is enabling stylistic rules. So this is a a debate in the world of linting in JavaScript and TypeScript where should you use prettier in combination with ESLint or should you just use ESLint? And there's actually an ESLint plugin called ESLint Stylistic that has all of the formatting rules of prettier and more that are integrated directly with ESLint. And there's a bit more opinions around line wrapping length and stuff like that. So if you want to enable those, you can actually just head to your Nux config and enable the stylistic setting there.
But you can also add other configs inside of the config. So right here you can actually pass in an object of options. And then for instance you get access to rules. And then from here you could enable or disable all of your preferred rules. You could also add other eslint plugins and import them into this file. But I actually like to use an opinionated preconfigured eslint plugin that comes from Anfu. And so if you head to Anfu's repo, he actually has a command you can run to install it. But because we're using it inside of the eslink configured for nux, we'll just do a manual installation. So we're going to add antfuzlink config as a dev dependency and then we can import it in.
antfu eslint-config
So in this file, we'll import it right after withnux and then we can actually just pass afuss config into the call to withnux because antfouse config returns an eslint config. But what's nice about antfoose config is you can further customize it. So you can specify if you like to indent with a twospace tab or a fourspace tab or if you like single quotes or double quotes and then there's a bunch of other plugins enabled as well. So I've done this so many times that I just have an ESLint config that I like to use that has all of my preferred stylistic rules and then all of my preferred other rules with their settings. And so what I can do is just grab this and throw it in here. But since we're in a nux application, it's using view. So within AntFU's config, they actually have a view option and we can just set that to true. and his config also works with a lot of other frameworks like there's a react setting and there's a spelt setting but we're in Vue so I'm going to enable Vue there.
Now part of the extra plugins that I like to enable are import sorting and then also file name casing. So I'm of the opinion that all of your files should be using kebab case and so this enables that. So if you create files with camelc case names it's actually going to throw a llinter error. Now there are other options here. You could set this to camelc case and then enforce camel casing for all file names or you could use snake case. Uh they also have an option here for cases. And then you can specify multiple here and say, well, I want to allow kebab case and uh snake case. So it it's pretty customizable, but like I said, I prefer everything to be in kebab case. Now, with all of these settings, we should be good to go. But what I also like is to have lint on save. So every time I save a file, it'll automatically add semicolons if I'm missing them or format lines if they need formatting. And AntFU actually provides a VS code settings file that has all of these settings for us. So on save run eslint. The other thing is for
stylistic rules like missing semicolons or using the wrong quotes or whatever else. A lot of times those errors can get really loud if they're in your editor. So this actually disables showing a llinter error for those, but it will just fix them whenever you save the file. So I'll grab these settings and then in here I'll create a folder called.v. And then inside of there, create a settings.json file and put all of those settings in there. The other thing this does is disable prettier and format on save because our llinter is going to handle all of that for us. Now, there's one more thing we need to do in order for all of this to kick in. If you press command shiftp and then search for eslint show output channel, you'll see if there's any errors for eslint right now. But there's actually one more plugin that we need to install the eslint plug-in format. And it can't do this interactively from that. So, we're just going to copy that name and then do a pnpmi- capital DSLint plug-in format.
And now that we have it, let's reload VS Code. And it should be able to kick in with all of those ESLint settings. So, if you do command shiftp reload window, let's open up that output channel. And there actually is one more error. So, if we scroll all the way to the top, we can see uh different instances of the plug-in nux import rules and antfu import rules. You might have forgotten to set standalone to false. So, if you look in the Noxdslint documentation, they talk about custom config presets.
And here, we're just going to tell it that it's not the only thing with all the rules and plugins. We're using Anfu as well. So, we can copy this setting here. And then in our NX config, we can add the setting here for ESLint to say, hey, you are not standalone. And then let's reload VS Code one more time. Now, we reloaded the window and it still didn't work, but we actually need to run the dev server. So when you run the next dev server, it's going to see that config option where we set standalone to false and then enable all of the other things to make it all work. And so with that now you should start to see some llinter errors. And so this is saying for import order, this needs to come before. And because we enabled lint on save, if I just save this file, it automatically adds those semicolons and then sorts the imports in the correct order. So that's looking good. Now, I kind of missed this in the Nuxdslint docs, but if you scroll down a little bit further, you will see there's an example here with the AntFu config, and they tell you that you need to set standalone to false. Now, we also want to add some lint commands. So, I'm going to grab these and put them into my
package.json. Now, below all of these other scripts, I'm going to add these lint scripts. And so, now we have a command that can just lint without fixing and a command that can lint and fix. So, from the command line, if I just do pnpm lint, it'll run that. We'll see that because we use the CLI, there are some files that aren't following our lint rules because we added all of the Antfu settings. But if I do pmpp lint fix, that will fix all of those and we should be good to go. Okay, so that looks good. But now I want to set up some pre-commit linting. So essentially anytime before I run a commit, it will run the llinter and if there are linting errors, it'll prevent me from actually committing. Now some people don't like this. It's possible to disable if maybe you're like in a workin progress feature and you know that the llinter isn't going to pass. You could disable it like oneoff, but I much prefer learning early before pushing to GitHub instead of waiting for my CI server to tell me.
pre-commit hooks lint
Now, there are other ways to handle this aside from pre-commit hooks. And actually, the ESLint module has a setting for this. It's called the dev server checker where in your settings you can set ESLint checker to true. And this will actually run the llinter with the build process. So, if you ever have any lint errors, you would literally see that in the web browser and it would prevent a build from running. Um, like they say here, this is nice if you know that not everyone is using the same IDE and you want to like expose those llinter errors. To me, this this is too much, right? I don't want my my app to crash if there's a linting error, but that is an option you can enable. So, what we're going to set up is a thing called lint stage. So, it will look at only the files that have been staged for commit and then run the llinter against those. And then we're going to combine that with husky, which is a tool for adding a pre-commit hook. So first for husky we're going to install it as a dev dependency and then we will init it.
After initing you'll get this husky folder which you actually do commit to your repo even though it has husky in the name because this specifically has the pre-commit hooks that's going to run. If you look at this you can see that by default it just has pnpm tests. We don't have any tests in our app. But what we want it to do is pnpm lint. So right before a commit it'll run the llinter and if the llinter fails it'll stop the commit from happening. So to see this in action is actually pretty hard because we've enabled lint ons save. So I'm actually going to disable this setting just for a second. So that way it doesn't lint whenever I save a file and then I'll have some llinter errors. So let's just say in my config here I'm going to remove this semicolon.
If I just run pnpm lint, we should get a llinter error that says there's a missing semicolon. Yeah, but let's try to commit this code now. So if I do a get status, I see what I need to commit. Let's stage everything. and then we'll try to do a commit. So we'll see right before the commit, it runs that command that we specified in the pre-commit hook and it stops us from committing. So if I do a get status, you can see that it it didn't actually let the commit happen.
But now instead of just running the llinter for our whole project, we actually only want to run the llinter against files that have changed because it's going to be a lot faster, especially as your codebase grows. If you're running the llinter for your whole codebase on every commit, that's going to take a long time. And that's where lint stage comes into play. And so with lint stage, it's going to only see the files that have been staged for commit and only run the llinter against those files. We're going to install this as a dev dependency. I'll use pnpm. And then now that we have it installed, we need to configure it. And essentially, we're just going to tell it that it needs to run that lint command that we specified in our package.json. So if we head to configuration, we can see you could create a separate lint staged files. I like to limit the number of config files because we already have a lot, but you can add this directly to your package.json. So inside of our package.json, JSON that tells it we should run PNPM lint. And so that will look at this task and then run it. So if you want to add any more options here, you can add them here. And then this is always going to run that llinter option.
And to test this out, I still have that missing semicolon and I disabled lint on save. So now if we run pnpm exec staged, we should see that issue with the missing semicolon. Great. But now let's just fix our whole codebase. So if we do pnpm lint fix and then if we add everything so it's staged we can see the stage files and then run pnpm exec lintstaged we can see that it passes. So if you're running into any issues with lint stage make sure that you've fixed all the files first and then it should get rid of any warnings or anything that you saw there. So this looks good. I'm going to go ahead and reenable lint on save in my editor and the semicolon is back because we ran the lintfix. But now for husky, we need to point it at lintstaged as well. So here in pre-commit, instead of just running pnpm lint, we actually want to run pnpm exec lint-staged. And so now anytime before we commit, it's going to run lintstaged and will stop us from committing if we
have any llinter errors. And one thing I'll point out is you can ignore these git hooks, right? If you do dash in or- no verify, that will not run the pre-commit hooks whenever you're doing a git commit. and that will prevent you from having to run it. Maybe if you're in like a work in progress feature and you don't care about llinter rules or anything like that. So this is fine with me and especially if other people are going to be contributing to this codebase and they don't want the git hooks, they can just pass in dash in.
git feature branch worflow
Okay, so we're looking good so far. But before we work on this CI pipeline includes linting checks, I do want to work on a separate branch and and commit the code that I have right now. Now, there's a lot of different ways to handle this, but one of the easiest ways is to create a branch with the number of the ticket or issue that you're working on. So, this particular ticket right here is ticket number nine. So, I'm going to check out a branch called TL-9.
So, TL is short for travel log. You could come up with a short code for your project and then dash the the specific issue that you're working on. So, we checked out a branch. I'm going to add all of my changes here and I'm going to commit them. say setup eslint and lint staged. Now lint stage does run and we have a successful commit. So if I do a git log, we have that commit here on this branch. Now the other nice thing about working on branches is you can push your code up to GitHub and if anyone else is on your team, they can see your current progress. So we'll actually push this up right now. I'll say get push origin TL-9 and that's going to create that branch on the GitHub remote and push all of my code there. So, if we head back to the repo, we should see that I have this branch that was created. And I can go ahead and create a pull request that says this should be merged back into main. Now, we're just working on a oneperson team.
So, this may not make as much sense, but this is good practice to get in because eventually you might be working on a team where you have to use this flow. So, I'm going to go ahead and create this pull request. And you can see that it's ready to be merged in. And with Versell, we actually have preview deployed. So if I click on visit preview, we can see what the app looks like with my current changes. Now I haven't changed the app itself because I'm just working on eslint config and everything else. But as we work on each feature, this is a nice way to get live previews of the stuff that you're working on, especially for like non-technical people on your team. So that's great. But we also want to run our llinter. So anytime there's a new commit to a branch or a new branch gets created, the llinter will run and prevent us from merging if there are any llinter errors. So we're going to set that up with GitHub actions. And we're going to do this just by manually specifying the YAML file. You can see they have a lot of different kickstarts, but if you head to the GitHub documentation, they have a section on building and testing Node.js, which is what we're going to use for our Next app here. And this is nice because their examples can run your tests or llinters against multiple versions of Node.js.
lint github action
For our use case, we're going to keep it simple and just run it on the latest LTS of Node.js. And so they have this example YAML file right here. So we're just going to grab that. And then in our repo, we'll create a new folder called GitHub. And then inside of there, a folder called workflows. And then inside of there, we'll create one called lint.yml. And we'll throw that codes inside of there. So by default, this will run on an Ubuntu box. They have a couple of built-in things that's going to just check out the latest code. And then they also have a preconfigured action that sets up the environment to use Node.js. And then we can specify the node version right here. And then by default, it runs all of these commands.
But in order to run the llinter, we first need to install dependencies. So we'll do a pnpm install. And then after that, we'll run the llinter with pnpm lint. And that should be all we need. But you can see that each one of these run commands is just another command to run. So you can create these workflow files that run tests or do builds or anything else. Now for our action, we want to run it anytime there's a new pull request or a push to that specific pull request. And by default, this will run on every single push to the repo. So every single commit to the repo, it's going to run this action, but we can limit it. So in their docs, if you go to trigger a workflow, they specify that you can run this action when an issue is opened or various other things. And for our purposes, we want to run the llinter when there is a pull request against the main branch. So here you can see on pull request branches and you can specify all the branches that you care about. For this app, we just care about the main branch. So I'll grab this and then just replace that here. And so now whenever there is a pull request to the main branch, run the llinter on that code.
Now we'll give it a better name. We'll just call this lint and we should be good to go. So since we're already working from that separate branch, I'm going to go ahead and commit this push up and we should see this kick in to the branch that we pushed it up to. So I have that workflow file staged. We're going to commit it and we'll see that it actually runs the llinter on that YAML file. And then we'll push it up to that branch. And now when we look at this specific branch, we should see it's running the llinter. And you can actually look at the progress and see that it it's going to set up the environment. And this actually failed because the default node environment only has npm. It doesn't have PNPM. So we'll have to figure out how to give it PNPM. I'm also noticing that it ran on node version 20. I forgot we actually want to update our node version right here to be the LTS or long-term support.
If you head to nodejs.org, you can see the current LTS is version 22. Latest version is 23, but we're going to stick to the LTS. So, we're actually going to set that to 22. Now, to get PNPM working, you can look in the PNPM docs. They tell you how to do this with GitHub actions. They specifically have this action setup available. So, we can just add it as another line in our YAML file.
So, right here, you can see they have install PNPM and they do that before setting up of Node.js. So, we'll just add this right here. Okay. So, now this action should have PNPM available and it should be able to run that install. So now I want to test this out. But this workflow of modifying the workflow file, pushing it up, seeing if it worked is very cumbersome. But there's actually this tool called ACT that lets you run GitHub actions locally. You don't have to keep pushing up to a repo to see if they worked. You can just run them locally. So if you look at their install guides, they have a bunch of different ways to install it. I'm just going to use brew because I'm on a Mac, but there's a lot of other ways to install it. Now, it's important to note to use this tool, you need Docker installed. So I actually have Docker running here.
It's ready to go. And this act tool is going to actually spin up some containers in Docker to do the same thing that's happening in the GitHub workflows. So here in their docs under usage guide, we want to run it for pull requests. So I'm going to run ACT pull request. And for initial setup, you're going to have to set up your image size. And I'm just going to go with medium. And it's going to start running it locally. So you can see that it's pulling that Ubuntu image. Now it's doing the PNPM setup and the setup node.
Now it's installing dependencies. And it failed. So that saved us from pushing up to GitHub to see that it was going to fail. But it looks like for some reason ESLint is looking at this PNPM store directory. This doesn't exist in our local directory, but it's probably because of the way that they set things up. But we do want to ignore that. So I'm just going to add an ignores field here inside of my ESLint config. And we'll say pnpm-to anything inside of there. All right, let's try again.
Should be a little bit faster this time because it's already pulled all of those containers. Sweet. So this is great. I am now fairly confident that if I push this to GitHub, it's going to work there as well. So, let's commit these changes. And then we'll push this up. And now, if we take a look at the pull request, it should be running. Yeah. So, it's running again. And we can take a look at the logs here to see if it works. And it looks like it completed. So, if we head back, we should see a green check mark.
And we do. Sweet. Now, you could take this a step further and only deploy to Versell preview if the linting pass. I'm not going to do that because it actually would require a custom workflow. Verscell doesn't support that out of the box. Essentially, you'd create another workflow file and then have it only run if the lint workflow passed, but we're not going to set that up for this project, but it is something that you could do. So, we set up the CI pipeline, but now before we can mark this as done, we need to merge it in. So, I'm going to merge this pull request, and I'm going to use squash and merge. So, this particular feature took three commits to get working. And if we just merged it in as is, we would see all three of those commits on the main branch. I like to keep my main branch as clean as possible. So squashing will essentially do that. It'll take all three of these commits, turn them into a single commit, and now we'll just see that one commit on the main branch. So we're going to do a squash and merge, and we don't need any of the extended description because all of that was a part of getting ESLint and lint stage set up. So I'm going to
confirm that that PR got merged in. And now Versel will actually deploy our main branch. So if we look at our main branch, it's nice and clean. We have the initial commit and then the eslint setup and then we can see that versell saw a new commit so it's actually deploying it. Now of course this is just a llinter setup. Our site hasn't changed but we're going to follow this workflow for every feature and every time we have a new working feature it's going to be deployed once we merge into main and we're good to go. So our latest commit was merged deployed everything is awesome. So back over on our board we're going to move this to done and keep on working. All right. Next up we're going to set up all of our UI. So we're going to set up Tailwind for our CSS. We're going to use Daisy UI, which is a Tailwind component library. And then we're also going to find a library for all of the icons throughout our app. So before we get started coding, let's check out a new branch. So I'm first going to check out main. And then we'll pull from our origin to get all of those latest changes that we just pushed in.
tailwind setup
So now we're back on the main branch. We have all of those latest changes with our workflows and our ESLint config. But now we'll check out a feature branch. So this is issue number 10. So we're going to check out a branch TL-10. So now let's install Tailwind CSS. Now if you look at nux.com and look at their modules, they actually do have a Tailwind module, but it does not support the latest version 4 just yet. There's an issue open for it, but we do want to use the latest version 4 because the latest version of Daisy UI, which we're going to use, uses Tailwind V4. So we can't use this plugin. But the manual setup is fairly easy as well. So if you head over to the Tailwind website and then go to the Nux framework integration guide, we can then install all of our dependencies. So we'll install Tailwind and Tailwind CSSV and we'll use PNPM for that. And then we can add Tailwind CSS to our Nux config. So up at the top we'll import that in. And then there's a Vit section of the Nux config where we
can pass in some Vit plugins. So we'll do just that. And then we'll need a main CSS file. So this tells us to put it in our assets CSS folder. And we can see if we look in the NX documentation under docs guide and then directory structure, they specify that you can have an assets folder. Now these are all the other possible folders you can have. You can see by default it doesn't have any of those. We kind of add them as we need them. So we are going to create an assets folder. Inside of there, I'll create another one called CSS. And then let's just create another one called main.css. Now, inside of that CSS file, we will import Tailwind. And this sets us up to go with the default Tailwind config. And then we're going to tell our Nux app to load that CSS file in for every page that gets loaded in. So in our NX config, we can specify a CSS setting. And now every page that gets loaded is going to load in that CSS file. And our dev server is still running. So let's give it a try. So, if
we try to add some Tailwind classes and then we'll update our app.view to not pull in either of those components anymore. Let's see if it works. So, if we head to localhost 3000, we've got ourselves a Tailwind app. So, it's pulling in the font style and the underline and everything else. So, Tailwind is set up and ready to go. Now, I want to set up Daisy UI. So, Daisy UI is a set of UI components that are built on top of Tailwind. And they have all kinds of things like buttons with default styling. And to use them, they have a class provided for you, just btn.
daisy ui setup
And then if you want to customize them further, you could use Tailwind classes as well. But they have all the things we would need for UI like cards and collapsables and nicely styled inputs and field sets and file inputs and all the things you would want in a UI. They've styled it by default and they've given you some nice simple class names to use, but it's using Tailwind CSS under the hood. So let's set this up.
And it's important to note that Daisy UI version 5 was released very recently and this is the switch to use the latest v4 version of Tailwind. So you're going to want to make sure that you're installing Daisy UI5. So first we'll add it as a dependency and then we can update our CSS file to add the Daisy UI plugin like so. And right now we are getting this error that it doesn't know what app plugin is. But we can tell VS Code that it should use Tailwind when it's looking at CSS files. So if you head to our VSS code folder and then our settings.json, JSON, we can add this setting which is file associations and say that anytime VS code sees a CSS file, it should be using Tailwind CSS. And with that, it should get rid of that plug-in error.
Now, another piece of editor config we want to add our recommended extension. So, if anyone else opens up our project in VS Code, we want to recommend that they have ESLint installed in the Tailwind plugin and also the Vue plugin because we're working in Nux. So, here in our VSS code folder, we can create a file called extensions.json. JSON and inside of here we can add recommendations and then list all of the extensions we recommend people have in here. So we want to make sure they have ESLint, we want to make sure they have Tailwind and the View plugin. And so now if anybody opens our project up in VS Code, if they don't have these installed, it'll ask them if they want to install them. And so now that we have Daisy installed, we can try using something. So let's just try adding a nice pink button to the page. So, I'm going to grab this secondary button. And then over in our app doview, we'll add that here and see if it works. Look at that. We've got a button. And you can see that Daisy UI has detected that I prefer dark mode by default. Now, let's set up dark mode support. Now, you see that it it's dark by default, but we can
actually lock this down because Daisy UI has a ton of different themes built in, each with dark mode and light mode. So, they have all of these. We're going to keep it basic. We're going to go with Daisy UI light and Daisy UI dark as our dark and light themes. But you can go through all of these and choose which one you want to use for dark and light.
But in order to do this in our CSS, we can actually tell it which theme to use depending on the user's color preference. So here whenever we set up Daisy, we'll say the default theme is the light theme and then if the user prefers dark mode, use the dark theme. But you can see if you want to make multiple themes available, you can just add that to the setting there. Or you could specify a different theme to use if they prefer dark mode. And now if I change my preferred color mode. So if I if I change my system settings to prefer light mode, you can see that Daisy uses light mode. And if I choose dark, it uses dark mode. Now later on, we're going to add a theme toggle so user can explicitly choose lighter or dark mode.
But for now, we at least get automatic theme detection. And lastly, let's set up UI icons. So for all of the stuff throughout our UI like on buttons and list items and stuff like that, we want to have nice little icons that indicate to the user what that thing is or what it does. So we're going to install an icon library. Now again has another module we can use and it's called icon.
nuxt/icon setup
And what's nice about this is it's based on Iconify. So Iconify makes it so that you can use basically any icon library out there. Whatever your preferred icon library is, you can use it with Iconify. So we'll go ahead and install this module. And again, we have to do pnpm dlx that. And that should have updated our nux config to include the nux icon package. And once you have this installed, you can essentially just pick the icon library that you want and then use that library name as a prefix whenever you want to specify an icon. So Iconify has a few different packages that you can use for this. I like to use the site called icons. So if you head to icons.js.org, this was actually built by AntFu. Surprise. But you can search across every available icon set that you could potentially add into your app.
Personally, I like to use Tableau just because they have over 5,000 icons. And since we're building a map application, they have a ton of these icons that look like a map or like location indicators or pins on a map. So, I like to use Tableau. But if you use this icons site and then let's say click an icon that you want to use, they'll give you the iconify JSON command you can run to make this particular icon set available. So if we run this command now we should have the tabler icons available to us and we can see that the name is tabler colon map. So if I copy that name then we can use next icon to bring in that icon. So this package makes capital I icon available to us. It's a component we can use anywhere and then we specify the name. So let's do it right here in this button. We'll say view map and then I'll bring in the icon component and then I'll say name is tableabler map.
And if we head back over to our app, we've got ourselves a nice little map icon. And so this is awesome because I can pull literally any icon from Tableau now, just as long as I know what the name is here. And if for whatever reason I wanted to pull from multiple component libraries, I could add that dependency as well and then pull in components maybe from another library if they're missing from this library. There's a few other options you can specify. You can see that you can pass in a style prop.
Um there's also like a size prop. So, if we set size to let's say 32, now we get a much bigger icon. Now, I did notice an issue where I wasn't getting errors if I was missing some of the props. Um, and this is the error that you should be seeing and I just downgraded the version of this plugin. So, by default, this installed version 1.11. I went to the previous version and the types are working again. I didn't see any issues open on the repo, but for now, we can just use the older version of the plugin. So, we're ready to go. anywhere in our app where we want to use icons, we can just search icons for the specific one we want. That's going to give us the name we can use and then we just pass that into the icon component.
All right, so we're good to go here. Now, there's one more thing I would like to set up. Unfortunately, it's not supported right now, which is a Tailwind plugin for ESLint. So, there's this plugin here. It's called ESLint plug-in Tailwind. And essentially, it enforces the rules of class name order for whenever you're using Tailwind classes. However, they don't support version 4 of Tailwind just yet. But there is an issue open on that plugin right now that mentions they want V4 support. And there's a draft PR that hasn't been merged in yet. So I'm going to add myself a to-do in my ESLint config so that if and when they add support for V4, we'll add that plugin to our ESLint config here. All right, that's it for this ticket. Let's go ahead and push up open a PR. So we'll say setup Tailwind and Daisy UI and icons. Now it looks like we have a few issues here. Some of these aren't autofixed in my editor. So I am just going to run a pnpm lintfix.
That should resolve most of those and then we'll make the commit. So stage everything and make the commit. Great. We'll push that up, create a pull request, and we'll add a note here that this closes issue number 10. We can wait for the preview deploy and all of our CI to pass, and then we'll merge this in. All right, let's test out our preview deploy. Look at that. We have a nice ugly app with a button on the homepage, but that means the the deploy worked.
Uh, and our llinter passed. So, I'm going to merge this in. And because in the description I said closes number 10, GitHub automatically detects that. And the moment this was merged in, it actually closed the issue that it referenced. So, we have 43 issues open now. And if we look at the board, it actually automatically moved that card to the done column because the PR that referenced it was merged in. But we're merged in. Close the ticket. And if we visit our production app, it has the latest changes. Next up, we're going to work on the landing page. So, we have this story here. As a guest, I want to see an engaging landing page that explains the app's purpose so that I understand what the application offers.
landing page
And so, we have a nice little wireframe that tells us everything we need. And we also have some checkboxes here to make sure that we include everything on the page. Now, to work on this, we're going to head to app.view. So, this is the entry point into our Next application. This is where we were messing around with Tailwind to make sure that it was working. But for this, we're actually going to use the layout system built into Next. So, in the Nux docs, you can see that there is this globally available component called Nux layout.
And so, what we'll do is our top level app component is just going to have the Nux layout component like so. And then we'll create a layouts folder. And inside of the layouts folder, we'll create default.view. And so Nux will automatically pull this in as the default layout whenever it sees that we're asking for it here with Nux layout. Now, for this layout, we will use the template tag. So this is how you define what your component is going to render. And inside of here, we're just going to have a top level div that uses some Tailwind classes to be full height.
And then also a flexbox. So we can flex the main content, the hero, and and put the navbar at the top. So we're going to make this a flex box. We'll make it min height of screen. So the layout takes up the whole page. And we're going to make this a flex column. Now within this, we're going to create a main element. And this is where all of our pages are going to get loaded into. So in view, we have this idea of slots. And so by placing the slot right here, once we set up our pages, every page is going to have this as the wrapping layout. And the page itself will get rendered right there into that slot. So to see that in action, we're going to need a page. And so in next, you can create a folder called pages. And they use file-based routing. So if we want a homepage, we can create index.view. And that will respond on the slash route. And in here, we'll create our template. And inside, I'm just going to have for now an H1 that just says hello world. But if we've set this up correctly, when someone visits our site, they're going to hit this, which will render the next layout.
And then the layout will render this, which will then render its slot. But to get our pages to render inside of that layout, we do need to use another component that's built into Nux called the Nuxed page like so. And so now, because this is rendered within the layout, it's going to see that we're requesting the index route. It's going to take this page and then render it right in the slot right there of this layout. And so if we head back to the browser, we now have hello world, but it's using that layout. So if we look at the inspector, we can see we have this top level div. We then have our main element and then everything is rendered right there inside of that main element.
So, one of the first things we're going to need on here is a navbar. So, if we head over to Daisy UI, they do have a navbar component. You can see this is like the basic one. And in dark mode, it's actually kind of hard to see against the background, but there are some other examples like these. So, I think I like this last one here, which is using a background primary. So, let's grab this navbar, and we're actually going to render it into the layout, but I want this navbar to be its own component. So, another folder that you can have inside of your Nux app is called components. And in here, I'll create a folder called app. And then inside of there, I'm going to create a file called nav-bar.view. Now, in nux, they have this convention where if there are any folders inside the components folder, your component name will be app dash and then whatever else is inside of there.
So, it's a nice shortorthhand. And so, I like to prefix any of my components that have a very general name like navbar with app so that anyone else that looks at my code knows that this is a custom component. It's not something that's just like built in. So, our navbar component is also going to have a template and then we can throw that navbar inside of it. And now that we've defined that component, we can add it into our layout. So, if we head to the layout, I want to put that navbar right above our main element. And you'll see that we get automatic imports of our components. And if I hover over this, we can see that it's actually a component that's defined over here. And global imports is one of the things that Nux has enabled by default. So, anything you put in that components folder is going to be available as a component throughout your app. So, now that we have the navbar, let's check it out.
There we go. So, that's looking good, but let's update the text here to just say travel log. And instead of a button, I'm going to make this a next link. So, next link is another built-in component in Nux. And this allows us to link to our various pages. But if the app is using client side routing, it'll handle that appropriately. And in this case, we just want to say go to the slash route.
So, if they click that in the navbar, it's going to take them to the homepage. So, that looks good. Now, we also want that button on the end of the navbar here. And if we look here in the navbar examples, they are showing an example of putting something all the way on the end. And that just has a class of navbar end. So I'm going to grab that. And then in our navbar component, we can throw this here. And we'll just call this sign in. And I think to get these to space apart correctly, we do need to add navbar start to that other button. So we'll call this navbar start. Yeah, that that's looking good. So this is all all the way on the end here, and then that's on the right there. Now we want our hero section. So, we want this area here that has the app title and description. So, in the Daisy UI docs, they do have a hero component. And this looks like exactly what we need. So, I'm going to grab this. And then in our index route, we're going to have the hero component.
So, let's just see what this looks like. It's looking pretty good. Now, I do want that hero section to only be in the top here. So, if we look at the styles that they provided, it has min height screen. I don't want that. Let's see what we get if I take that off. Yeah. And so, now we can see it's pushed up a little bit. Now, I also don't want it to be full width. So built into Tailwind is a class called container that sets the max width depending on device size. So that's what I want to use here. So we're going to set this to container. And then you'll see it's pushed over to the left. And so we can also add some automatic margin on the X-axis. And that should shift it to the center. Yeah. So that looks good.
And then according to the wireframes, the hero section should be pushed down a little bit. So I'm going to add some margin top. So right on here I'll do margin top and let's go with four. Yeah. So that's looking good to me. Now let's update the content. We'll add our text in there. And then this button is going to say sign in. And for the button, we're going to use button accent, which is like a green color like that. Yeah.
And then just to be consistent, I'm actually going to make this button at the top also be button accent. So back in the navbar component, we'll do button button accent. Awesome. And then lastly, I want this hero to be just a little bit taller. So I'm going to give it some min height. And so back over here on the hero, I'm going to give this element with hero content class. I'm going to give this a min height of something pretty big. Yeah, let's go as big as we can. Let's go like 96. Yeah, that's better. It's got some breathing room and it's responsive by default. So, because we're using that container class, it actually resizes according to screen width, which is great. Now, we could darken the background of this card here just so it's more differentiated. So, let's try like BGBase 300. That's a little bit better. And what's nice is all of these styles should respect dark mode and light mode, right? So, if we switch back to light mode, you'll see that this is how the app looks in light mode, but we didn't have to do anything special for darker light because Daisy UI has both the dark and the light theme. So, we have our hero section feature explanation. We've got our sign up and login button, but we need to add those GitHub icons there for signin. So,
right here, I'm going to add that icon component. And then let's head over to icons and find a GitHub icon here in Tableau. We have a few different ones. Um, I like the non-filled one. So, we'll use this. So, on the icon, I can set the name to Tableau brand GitHub. That's great. Let's increase the size a little bit. Let's go like 32. A little bit smaller. 24. Yeah, that's perfect. And just to be clear, the wireframes don't have this, but I am going to say sign in with GitHub just so it's a little little more clear. Awesome. And we'll add that exact same icon and text to our navbar element as well. Sweet. It's looking good. All right. Check that off. And uh we'll commit make a PR. We have a landing page. Now I do want to commit this to a branch for this feature. And this is issue number 11. So we'll check out a branch called TL-11. Check it.
Yes, these are all of the things that we've changed. Add a nice commit message. It's going to lint for us, which is good. And we'll push it up. Now we'll open a pull request for that branch we just created. And we'll add our comment here that says it fixes number 11. We'll wait for the preview deploy and the llinter to run. and then we should be good to merge. All right, let's check out that preview. Look at that. It's coming along. We have ourselves a landing page and the llinter passed. So, I'll just squash this, merge it in, and it will deploy. All right, next up, we're going to work on light and dark toggle. So, as a user, I want to toggle between dark and light themes.
theme toggle / color mode
So, we'll have a theme toggle button in the navbar, and it'll respect the system theme by default. And if they change their theme, that'll be respected when we come back to the website. and it shows a nice sun and moon icon. Now, Nux actually has a module in its ecosystem available for this. It's called color mode. So, this is it. If we check out the documentation, this makes it super easy to add dark and light toggle. So, we can add the module with this command.
And before we do that, let's go ahead and check out a branch. So, we'll head back to main, make sure we're synced up, and then we'll check out a new branch for this feature. So, TL-12. What's the issue number? Yes, TL-12. And then we'll do a pnpmdlx of nuxy module add color mode. And so that finished. And if we check out our nux config, it added the color mode plugin.
And if we look at their docs, they actually have some hooks available to us. So they have this use color mode. So we can detect the current color mode. And this also has a way of setting the color mode. So we want a toggle icon that will then use that hook to change the color mode. Now, Daisy UI has a built-in component called swap that allows you to do cool stuff like this. So, you can have it so that it automatically animates between the icons. And so, this is what we want.
It's almost exactly what we need, except they're specifying the icons here. So, we'll just grab this. And in our components, let's create a new component called theme toggle. Create a template. And we'll need to replace these SVGs here. So, if we head back over to icons, let's look for a sun. I like that one.
And so we'll just replace this SVG with our icon where the name is tableabler sun. And then we'll do the same thing with the moon icon and make this tableabler moon I'm guessing. But let's see what what moon icons we have available. Uh I like the filled in moon. Yeah. So moon filled. And then the way that it changes between these two is with a class name. So if you look back at their docs, we can see that when it's on, it's the sun icon and when it's off, it's the moon icon. So we'll add those classes here. Swap on and swap off. Now, let's pull this theme toggle button into our navbar. So, we're going to put this right beside the sign-in button, and we'll pull in app theme toggle like that. And we have ourselves a little toggle. Now, it's not actually hooked up to the state yet. And we need to work on the styles, but we're on our way. So, first, let's increase the size of the icons. So, let's try a size of 24. It's probably going to be the default sizing we use for most icons in our app. Let's see. Yeah, that's much better. And then, let's just add some margin on the left and right. So we can do
MX4. And now we have some nice margin. Sweet. But now we need to actually hook it up to that color mode module that we added. And if we look in their docs, we can pull in color mode using the use color mode hook. So for this component, we're going to add a script tag. And we're going to set the language to TS, which is TypeScript. And we're going to use script setup. So this is the modern way of building components with Vue.
Essentially, it gives us composition functions like hooks. So for instance, we can say color mode is use color mode. And the color mode module also made this hook available globally. So that's why we're not importing it. It's autoimp imported for us. Now we want this checkbox to basically bind to the underlying color value here. And for that we're going to use our own computed value. So I'm going to create a computed value called is dark and we'll use computed which is built into Vue.js. And essentially computed accepts a function.
You can have some logic in there but then whatever is returned will be the value of this variable here. And if its dependencies ever change, this will rerun. But because we want to hook into color mode here, we actually will just specify an object with a getter and a setter. And then behind the scenes, those getters and setters are going to get called, which we in turn can call color mode. So if I just pass in an object and specify get, now I can specify what happens when we get the value. And then I can also specify a setter, which takes in the value. And then in here, I can determine how we can set the color value. So, git is fairly straightforward because we just want to return color mode value. And in this case, is dark would be true if the color mode value is dark. So, that's great.
But now, whenever we set is dark, we want to update that behind the scenes. So, we can set color mode.preference to be either dark or light. And the value here is going to be bound to the checkbox. So, value is going to be true or false. So, if value is true, then we want this to be dark. Otherwise, we want this to be light. And so now we have this nice little computed value where if I say is dark equals true, it's going to call this setter which behind the scenes we'll call color mode and then update the the preferred color mode behind the scenes and then anytime we retrieve the value of is dark, we're going to grab that underlying value to see if it's equal to dark. Now built into view is a directive called vodel and I could just directly bind to this computed value like this. And so now when I check the checkbox is dark will call the setter and then update the color preference behind the scenes. So, let's give it a try. Let's actually see if this works.
And it doesn't. But let's look at the inspector to see what this is actually doing. So, when I click this now, initially I wasn't seeing the change in the dev tools. I just had to restart the knuck server. So, because we installed that new plugin, the build was stale. So, restart the dev server. But now, whenever I click this, you'll notice that it's actually changing the class property of HTML to be dark mode, light mode, dark mode, light mode. So in order to hook this up with Tailwind and Daisy UI, we need to actually set the data attribute on the HTML, not the class attribute. And if you look in the Daisy UI docs, you can see that they specify if you do data- theme and then the theme, that's the theme that will be set. So what we need is for this color mode plugin to set the data attribute.
And if you look in the color mode docs, they have this option here called data value that lets you add a data set to the HTML. So instead of doing class equals dark, you could do data- theme equals dark. And that's what we actually want. So if we head back over to our Nux config, we can add a configuration here for color mode. And here we can specify data value. And we'll do theme because then it will be data- theme equals dark or data- theme equals light. And that should be all we need to hook this up because now look at that. It's adding that data attribute there. So Tailwind and Daisy UI can actually hook into it.
But now we we need to make sure that this respects the user's system settings whenever they load the page. And so because I've clicked this a few times, Nux color mode actually puts a value in local storage. So if you look in local storage, you'll see a value set by Nux color mode that says dark. But if I delete that now, when the page loads, it should use my system preference. And right now, you can see Nux color mode is set to system. So if I change it to light, this automatically reacts. And because it's set to system, it we can see it as light mode. So, next color mode already respects the user's specified style preference. Sweet. So, we've got this all set up. And the other thing to note is this persists across sessions, right? I haven't closed the browser tab, but because it's set in local storage, if I close it and then reopen it elsewhere, it's going to use the user's preferred setting that they set the last time they were on the site.
So, let's commit all of our changes. And I am noticing that anytime we add a new dependency, we do need to run the llinter so that it lints our lock file in our package.json. So before I even run my commit, I'm going to do a lint fix. And now I'll add everything and commit it. Push that up to this branch.
Create a pull request. Approve the pull request. Merge it deploys. You get the picture at this point. Now next up, we're going to work on a way for working with our environment variables in a typesafe way. So we're going to use Zod to do this. And I like to set up my apps so that if I'm missing any of the required environment variables, the app doesn't even start. So that way you're not trying to chase down an issue. You know immediately what the issue is. Now, Nux actually comes with built-in support forv files. So, anyV file in your Nux app, it'll automatically detect that and then load all of those environment variables and then make them accessible inside of your server side code. And it automatically does not make any environment variable accessible in your client side code unless you use their runtime config. So here under going further. So with this you must specify in your runtime config in your nux config any variable that you want to expose to the front end otherwise nothing is accessible. So we get that for free and later on if we do need any environment variables in our front end we'll have to add them to our runtime config like this. But for now we can
typesafe env with zod
just work with our env. So first up let's go ahead and get back to the main branch and check out a branch. So we've got all the latest changes and then now we're going to check out a branch for TL13 I would assume. Yeah, issue number 13. And to define our ENV schema, we're going to use a tool called ZOD. And so Zod is a schema validation tool and allows us to create schemas like this.
So this defines an object with two properties, name and age. And then you can actually get a TypeScript type out of it. And you can run the validator.parse, and it will check to see if anything you pass into it has all of the required properties and they match all of the schemas that you've defined. So we're going to use ZOD for this. Let's install it as a dependency. And now we'll create our type safe env.
So in nux there also is a convention to have a folder called lib. And you can put reusable things inside of here. And so I'm going to put an env.ts here inside of lib. And this is where we're going to define our zod schema. So first we'll import in z from zod. And then we'll define our env schema which will be z.object. And then we can specify all of the environment variables that we want to exist. Now, right now we don't have any because we're not working with a database or off or anything else, but we can set up our node env. So, this is a convention when your app is running in a node environment. It can see whether or not node
enva and this will be z.infer and we can pass in the type of this validator. So if I say type of env schema, this is a utility built into ZOD. And you'll see this is just a TypeScript type that actually is what we've described here. But ENV schema itself is actually a validator where we can pass something into it to be validated. Now, in order to use this throughout my app, I actually want to parse process.v to check to see if all of these environment variables exist on it. So I'm also going to export default enva.parse and then pass in process.env.
So whenever this file is initially loaded, it's going to take process.v that has all of the environment variables that have been loaded in and then run them through this validator and if anything is missing, it's going to throw an error. But you'll notice right now I actually have a llinter warning that says unexpected use of process.env. So if you look in my ESLint config, this is one of the rules that I enable by default. So no process environ throughout my application, I don't want any other piece of code to access process.env. I always want them to use this schema here. So that way it's using the validated version of it.
So I am going to disable this llinter rule here, but everywhere else in my app, I want to get a llinter error to make sure that I'm importing from this file to use the validated one. Now, another llinter error that I like to turn off, I'll actually update my default config to have this, but right now we get a a TS no redeclare llinter warning, but I actually do like to define types with the exact same name as a variable. So I'm actually going to disable that rule across my project. So here in my eslink config, I can say ts no redeclare and then just turn that off. And if you copy pasted my example config, you should already have this setting because I it'll be updated by the time you're watching this video.
Okay, so that looks good. Uh now the one spot where we want to run this is when we start up our next app. So the easiest way to do that is in our NX config because this is going to be the first thing that loads before our app even starts to start up. And so in this file, I am just going to import this because when we import it, it's going to run the parser and if that environment variable is missing, it's going to throw an error. So inside of our nux config, I'm going to import that specific env file.
Now, I am going to use a relative path import. Uh you actually do get import aliases by default with whenever you set up a Nux app, but whenever this config file is running, it doesn't have those aliases just yet. So we're going to just import it directly. But now that this is specified in the Nux config, if I try to start up the app, everything works. But maybe that's because nodev is defined by default. Um, let's give this a try.
Let's actually let's add something completely random and then see if it breaks. So banana. Does the environment variable banana exist? If we restart this, yes. Okay. So now now we can see that apparently nux sets node env by default. But for all of our other environment variables that we're going to add later on, we do want it to crash just like this. And you can see by default the error isn't amazing to look at. So I actually have a utility function that I reuse in a lot of my projects that just takes a zod error and makes it nice and readable. And that's this. It's called try parse env. So you can essentially pass in the env here and the schema you want to validate it against. But if it errors out, it constructs a nice readable message and then we log that to the console. So I'm going to add this into lib as well as try parse env. and then we can use it in our env. So before we call parse here, we're going to call try pararse env with our env schema. And by default, this
function will use process.v if you don't pass anything in. And really all this is giving us is a nicer error in the console. You don't have to do this if you're okay with this odd error. But now when we start up the app, it shows it as nice and readable. Missing required values in yourv banana. So I like to add this just so they're slightly more readable instead of just being a full zod error. Okay, for now we can remove banana and everything is ready to go. So in any of our future features if we need to add environment variables, we're going to add them here first to make sure they exist whenever anyone is trying to start up the app. And so I can check both of these off, make a pull request, commit to my branch, run the pre-commit hooks, create a pull request, and then wait for it to deploy and then merge the pull request. I'm not going to show all of that at this point because we do it for every feature, but that's what I'm about to do. Right. Next up, we're going to set up our database. And for this we're going to be using Drizzle and Terso. So I have an example schema here and this is the schema that we're going to implement. I do have the user table on this schema but we're not going
db setup
to add that until we set up O because the tool we're using for O actually provides that schema for us. So for now we're just going to set up our schema with these three tables. We have locations which are the top level places that you'd like to visit. We then have location logs which is a specific time that you visited that location. And then for any log, you can have as many images as you'd like attached to that specific time you visited that location. And so, like I mentioned, we're going to be using Drizzle OM and we're going to be using Terso. So, Terso is built on top of SQLite and they have a really generous free tier. So, you can have up to 500 databases with 5 GB of storage, 500 million reads per month, 10 million writes per month. So, it's a very generous free tier. we're going to be using that. But when we're running locally, we'll be able to talk directly to a SQLite database and not have to talk to the cloud when we're we're running development things, which is my preferred way to work because a lot of these hosted services, you typically will potentially have to create an instance for like every one of your
developers or all of your developers are sharing the same instance. I like that we're going to be able to work completely locally and then when we're ready, we'll deploy to Terso in the cloud and our deployed instance of our app will talk to Terso in the cloud. So first we need to get the schema defined and initialized but we're going to follow the getting started here in the drizzle docs and we're going to head to the section on terso and for required packages we should just need drizzle o and libql client because nux already hasenv installed behind the scenes. So let's get back to the main branch and then we'll check out a branch. This is issue number 14 like so. And then we'll install these dependencies. We'll also add DrizzleKit as a dev dependency because that is what will generate our migrations and also run them against the database. So we're going to add Drizzle Kit as a dev dependency. From there, we're going to need some environment variables. So we'll grab these and first up, I'm going to add them to my type safe env. So in here, we're going to
drizzle setup
have terso database URL, which is a string, and then the O token, which is also a string, like so. And then from there, we can set up our Drizzle connection. I'm going to put this in the lib folder. I'm going to create a new folder called db. This is where all our database schema and connection and migrations is going to go. And inside of there, I'll create index.ts. This will be our main entry point and the connection to the database. So, we can copy from this example. Like I mentioned, we don't need to do anything with because next takes care of that for us. So, we can throw this in here. And then now instead of using process.env, we can import our type safe env. And in this case, we will use alias imports. So if I go to tildy/lib/ env now I have my env and I can pull it in to our connection settings here and I don't have to use any typescript assertions because by the time our code reaches here we've validated that these environment variables actually exist. And then lastly I'll export the DB as the default export. So that way any other file that
imports from here is going to get that drizzle connection. Next let's work on our schema. And in this case, I'm just going to define one table for now and make it super basic, get everything working, and then go back in and update the tables to have all of these fields that we've specified. But I just want to make sure everything is working before we get too far. So, here in the DB folder, I'm going to create a folder called schema. Now, I like to separate out my tables into separate files. You don't have to do this. You could define everything in schema.ts, but I'll show you how I set things up here. So, I'm going to create a file called location.ts. This is going to correspond to the location table in our database.
And then we have some default values here. We'll call this locations on both spots. So this is the name as it will exist in the drizzle schema. And this is the name of the table inside of our database. We do want auto incrementing ids. And then for now it's just going to have a name column. So we're going to keep this super basic for now. Make sure our connections working everywhere. And then we'll go back in and add the rest of the columns. Now to get all of our tables into a single schema file, I'm going to create a file here in schema called index.ts and then export each one of the tables that I defined. So I'll say export star from and then pull in location. And so now this one schema file is going to have our location table. But as we add each other table to this folder, we'll export it from this file as well. And now that we have that schema, when we define our connection here, we can pass that schema in. So we'll pass in schema, but we'll import star as schema from that schema file.
And by passing our schema in here, later on, if we want to use the OM style of querying, it'll be able to do that because it knows about all of our tables which exist within that schema module. And then next up, we'll define our drizzle config. So the drizzle config is the thing that will actually create our migrations and run our migrations. So we'll copy this example file. We'll create a file called drizzle config.ts.
throw that in there. And now we'll pull from our type safe env. So we'll import env. And again I am going to use relative paths here because it potentially won't use my path aliases. And then from there I can pull those values in exactly like so. Now I like to put my migrations in the same folder that I have all of my other stuff defined here. So in the out option I'm going to specify lib db migrations. And so the m migrations will get created there. And then we can point it to our schema which is in lib db schema/index.ts because schema.index.ts is going to have all of our tables exported from it. For dialect we're using terso. And so now I want to generate the migrations just to make sure that everything is working. But we do need to create av file. So we'll need thatv and we'll need to specify all of these options here. So in this case, node env is development and then we'll need to get a database URL and an O
turso local development
token. Now when you're running locally, you could technically put in a remote TRSO URL here, but I want to be able to do everything locally without even talking to anything in the cloud. And Terso actually provides a CLI for that. So if you head to their docs and click on local development, you can see that they have the Terso CLI. Now, there are some docs here specifically for the Terso CLI, and there's lots of different ways to install it. They have the install for Windows, Linux. I am on a Mac, so I'm just going to run the brew install to get the Terso CLI locally. So now with the Terso CLI installed, we should be able to run this command and then we'll just get a locally running instance of lib SQL. Great. So we have the URL to connect to here. And essentially when we're running locally, we don't need any O. So we're going to add some logic in our connection that says if the node env is development then don't use an O token. So first up in our env we're going to add the terso URL there. And then in our drizzle config we'll say if env.node env is equal to
development then undefined otherwise use the off token that comes from our environment variables. And we'll do the same thing when we're setting up our connection here with drizzle. So if env.node env is equal to development then do not pass in an off token otherwise use the off token that was specified. And so now with that we can attempt to generate the migrations. So we'll leave this running in this terminal in a new terminal. If I do pnpm drizzle kit generate that should generate our schema. Great. And that lives here as a SQL file. But now we can try to apply this migration to this local DB file. So if I do pnpm drizzle kit migrate, if everything worked right, it should have communicated with the server running here. And then we now have a database with a location table inside of it. To test it, if we do pnpm drizzle kit studio, it's going to fire up the studio and point to that local
DB. So we do have a migrations table and that location table. So everything is hooked up and working. So, what I'm going to do is actually delete the migrations folder, delete that local DB folder, and then we'll build out the full actual table schema before we apply it. So, let's just delete this migrations folder. And then I'm also going to delete this local DB. But while I'm thinking about it, we should add local DB to our git ignore. So, that way we're not committing that SQLite database. So, I'll just say local. DB star. Anything that starts with local.DB, DB. We do not want to commit that to git because it's just our local database file. And another thing we should do is instead of needing to run this command manually every time, let's add it to our package.json so it's easy to spin up. I'm going to create a task called dev db and then throw that in there. And so now anytime I run pnpm rundev col db, it'll start up that terso server. Now typically I want to run both of these at the same time. And there's no built-in crossplatform way of doing
that. So we're actually going to use an npm module called concurrently. This will make it so we can run both of those things at the same time, but it'll work on any operating system. So, let's install concurrently. And then you can see for tasks, we can say concurrently and then specify the two tasks that we want to run. And so now whenever we do pnpm rundev, I actually want to do concurrently. We'll do nextdev as one of them. And then we want to do pnpm rundev db for the other one. So that way both the database and our next app are running behind the scenes whenever we do pmppm rundev. And to test this out, we'll do pmppm rundev. We can see there's our terso app, the logs from our terso app, and then everything else is coming from next. Now, one more piece of configuration we want to add here for drizzle is the casing because when I'm working in my typescript app, I like to use camel casing, but my database itself, I want it to use snake casing.
So here I can specify snake case. And this will allow me to specify my column names using camel case, but they'll get converted into snake case whenever it's quering the database. We'll do the same thing in our drizzle config. So here we have a casing option and we'll specify that as snake case as well. So when it generates those migrations, it's going to use snake casing for all the column names. And so we've done a lot, but so far we have our connection configured, we've documented our environment variables, and we technically have a migration system. we really just need to work on that database schema and then apply it to the database. So if we look at the schema, we can see that every location also has a name. So I'm going to specify name and this is going to be text and I want this to be not null because it should not be blank. Next up is the slug. So this is like the human readable no special characters thing that appears in the URL and that will exist for every location as well. So we're going to set this to a text column. it will not be null. And we
db schema
actually want this to be unique because I don't want two different locations to have the same slug because it's used in the URL. Next up, we'll also have a description. We'll make this text. And we will make this optional. So, you can leave off the description if you'd like. And then next up, we have latitude and longitude. And these are going to be floating point numbers. Um, I'm going to abbreviate them as lat. And then we're going to use real, which comes from SQLite to give us a floatingoint number.
So I'm going to use lat and long because this is a location-based application. We use lat and long all over our codebase. So it it gets a bit cumbersome if we're specifying latitude longitude everywhere. So we're going to call these lat and long. And we're going to make sure that these are not null because they are required for a location. And then we will need a user ID. We're going to leave that off for now because like I mentioned, we're not going to add the user until we add the O integration. So no user ID column for now. And then we need a created at and an updated at field. And in this case, I am specifying it with camel case because like I said, we specified snake casing. So, it's going to convert this to snake case inside of our database. Now, SQLite does not have a date type. We're just going to use integers. And we're going to say this cannot be null. And I'm going to specify the default option as right now.
So, dollar sign default is actually a function that's just going to run inside of your code here because there isn't a way to specify inside of SQLite code that should run when a row is inserted. But because all of our queries are happening from our app here, we can specify that when we create a row, we can use date.now. It'll have the current time on that column. Now, Drizzle actually does support setting the mode for integer. So, here you can set mode and do things like time stamp or time stamp millisecond, and that will make it so that the data that you get back actually has a date object on it. But I actually prefer using uh timestamps because it's easier to sort things because it's a number. Once I have a timestamp value, I can pass that into any date library to format it. So I actually prefer storing my dates as integers. Now we'll do the same thing for updated at, but we also have the on update function that we can specify. And so this will automatically update that
field for us and set it to be date.now. So anytime I insert a row, I don't have to specify created at. It's going to use the current time. And then anytime I update a row, it's automatically going to use the current time. Now, before I forget, I actually prefer to have my model names and table names use singular, not plural. So we're going to call this location, not locations. You can of course call it whatever you want, but I like to stay consistent.
Everything is singular because it represents an entity, and then each row is an instance of that entity. So the rows are per plural but the schema itself is singular. That that's bas that's just my preference. Okay. So now I'm just going to copy that and then rename it to location log. And then we can start defining our location logged table. So we can see a location log has a name and a description but it also has started at and ended at. And this is essentially when you visited that location. So we have ID, name, description, and then we want started at and ended at. And I'm not going to set a default value for these because they'll be specified when the user is creating these location logs. So we'll call this ended at. We'll rename this to location log and location log. And then the location log will need a foreign key reference back to the location table. So it's going to have a location ID. So here we'll specify location ID. And this will be an integer that is not null and references the ID column in the location
table. And the way that we do that with Drizzle is we just need to import that location table and say ID like so. And so this is going to create a foreign key reference so that any row that gets inserted into location log will have to have a location ID and that location ID must exist in the location table. Now just like before, we're going to leave off user ID for now because we'll add that once we have all of our O integrated and we have the same created at and updated at columns. All right, next up we need to define this location log image table. This is going to store each image that's associated with a specific time that you visited that location. So, let me copy this file over to location-log image. And then we'll rename it to location log image. And this has a text column called key. So, we're going to be storing our images in S3 compatible storage. And so, the key of the image will get stored there, which is just like a path. And then we can host our images anywhere. and we'll have an environment variable that
specifies the specific URL, but the key will be stored in our database. So key is text and not null. It then needs a location log ID. So we're going to associate this image with a location log. So we'll give it a location log ID and this will instead come from location log ID. And we'll pull that in from the right spot like so. And so we've got ID, key, location log. Again, we're going to skip the user ID for now. And we got our created at and updated at. Now before I forget, we need to export these two tables, location log and location log image from our schema file as well. So right here, I'll say export everything from location log or location dash log.
And then also export everything from location log image. So all of our tables are exported here. And then when they're used in the schema here, it'll have access to all those tables. Okay, so schema is defined. Now it's time to run those migrations and get that database created locally. And now I can do a pnpm drizzle-kit generate. That will look at our schema file and generate our migrations. Looks like it did. If we head to the migrations folder, we should see a SQL file that defines all of those tables. Great. And now we can run the migrations. So I'll start up my local DB. So that's running. And then I'll do a pnpm drizzle kit migrate. And that should create the tables on that DB. It did. To test it out, if we do pmppm drizzle kit studio, it'll launch the studio and we can make sure all of our tables exist in there. Sweet. So, we have the migrations table, but we've also got the location, location log, and location log image. And I'll remind you
that we updated our git ignore to not add those local DB files because those are going to get created when we spin up the local DB server, but we don't want to push those up to GitHub. Now I've staged everything for commit but I actually want ESLint to ignore this migrations folder because I don't want it formatting these JSON files or the SQL file and it doesn't use kebab case for those file names. So I just want to ignore that folder completely in our ESLint config. I'm going to add another ignores here that says starstar/migrations/star. So ignore everything in the migrations folder. Now if I do a pnpm lintfix hopefully it doesn't find those files narrow. Yeah.
So everything's linted. It didn't care about that folder. Great. Now I can add everything and commit. Sweet. Push up to that branch. Merge it in. So, initially pushing actually failed and I had to do a couple of things. So, first of all, we had to specify our environment variables over on Verscell, right? Because we made the Terso database URL and Terso O token required. So, inside of Verscell, we went to the settings for this project and then added these as environment variables here. Right now, we just set them to local host because we don't actually need to talk to a database.
set environment variables on vercel and github actions
They just need to exist for the build to work. So, when Verscell is creating that preview deploy and the final deploy, it's going to use those values. But we also needed to make those environment variables available to our GitHub action. So, I found this section of the docs about secrets. Inside of the Git repo, we went to settings and then environments and we created an environment for when we're running the llinter. In this case, I called it build. And inside of that environment, we added two secrets, the Terso O token and the Terso database URL. Then now that we have that environment, we updated our GitHub action to use it. So if you check this out, right under this job for linting, we set the environment to build. Now it has access to those environment variables. And then we need to expose those environment variables to the build itself. And so I have an env option here and I'm pulling in those two secrets. So that way the npm install which does a nux build to generate the types will have access to those environment variables. Uh so this took me a second to figure out. You can see
by my commit history. It took a few tries before I got the right syntax inside of the action file, but it's working. So to recap, update your env with this and the build. Create your environment and add the secrets on GitHub. And then also add those environment variables in the Verscell dashboard. And from there, we're good to go. So our preview deploy worked. Our llinter passed. Now we're going to merge everything in. And this is a really good example of using squash because I had all these little commits trying to figure out the syntax for the action file. If I do a squash, all of this is going to show up as a single commit and I don't have all of those work in progress commits. So we'll merge that in. Move on to the next thing. Next up, we're going to work on setting up O. And for this, we are going to use better off. So I've used a lot of different O frameworks out there. I was using ojs for a lot of things, but I have really been liking better off. It's configurable in just the right ways. It supports a ton of different frameworks and has database adapters. It's really great to work with. So, this is what
auth setup with better-auth
we're going to use. If we head to their getting started, we can do an installation and we're going to run through all of these commands. But if you check out integrations, you can see all of the frameworks they support. If you check out Nux, they tell us first run through the installation and then there are some Nux specific things we can do afterwards to get it integrated. So, let's head back to installation.
branch. Sweet. And then we'll check out a branch called TL- 15 because this is issue number 15. All right. We'll add better off as a dependency. And then we'll need some environment variables. So, we need a better off secret. This is the key that's used to sign our session tokens.
So in our type safe env we're going to add another option here for better off secret. And then in our env we'll specify a value and this will just generate a secret for us which is fine. This is local development so it doesn't need to be too secure. And then we'll set the better off base URL as well. And we'll specify this in our type safe env.
Okay. So those are looking good. And now we need a better off instance. So it looks for it in three different locations. The project route, the lib fold, the lib folder or utils. We're going to put it in lib because that's our convention for next. So we'll grab this better off instance. And then in the lib folder I'm going to create an o.ts file. Throw that in there. Now we can configure our database. So we are using SQLite. And better off comes with a couple different ways to integrate the database. They have just the database adapter. They allow you to pass in an instance of a database. They also allow you to use a lib SQL dialect, but since we're using Drizzle, they actually have an adapter for Drizzle that will generate the Drizzle migrations for us.
So, we actually want this set up here. And then we need to pull in our Drizzle instance, which is in DB/index like so. And it is a default export. Okay. So that's the drizzle instance that we defined earlier that actually connects to our database. And then we pass that in here. And now we want to tell it to use SQLite. Awesome.
So now that we've hooked everything up, better off we'll generate the migrations that create the user table and the account table and all the other stuff it needs. So we can run this command here and we'll do pnpm dlx that command. And apparently their CLI tool does not support path aliases. So we will fix that.
Essentially, our DB file is using an alias path, but it's already in the lib folder. So, this is actually just go up one directory and grab the env. So, that should be fine. And so, now if we try to generate them. Cool. So, do you want to generate o- schema? Let's say yes. And then it generated the schema for us.
Here it is. And I am going to move it into the schema folder. And of course, my llinter won't run on it and make everything look nice. Now, Better Off does come with various plugins that might actually need to modify your schema. For our off setup, we're not going to be adding any plugin like that, but if you are, you might need to keep this file in the root so that better off can see the schema to modify it, but I haven't worked with any of those plugins, so your mileage may vary. So, I'm going to pull this off schema into my schema directory. And then I'm just going to rename it to O. We'll run our llinter. And then I'm going to update a few things. So, by default, Betteroth generates a random text based ID for all of these columns. I actually prefer to use integer IDs. So, I'm going to replace these and we'll do it the exact same way that we're doing it for the rest of our tables. And there is a setting in better off to tell it to not use that textbased generation. And we'll pull in int from SQLite core like that.
And so, if we check the docs, there is an option under advance called generate ID. And we're just going to specify that to false. Now, you don't have to disable this. I just like to have consistent ids throughout my database. And because all of my other tables are using ins, I want these account tables to use ins as well. Now, this schema actually uses the old way of drizzle where you specify both the name of the column and then the name of the column here. It's redundant. So, I am going to remove that as well. So, that looks good. Less code is good code.
And then lastly, like I said earlier with our timestamps, I like to just work with them as numbers. I don't want them to be dates. So, I'm actually going to remove the mode here. Now, this doesn't break any of the better off internals because it can still compare all of these numbers. But now all of these timestamps on here are going to just be numbers and we can treat them as the Unix epoch and then convert them if we need to. Okay, so this is looking great.
Now we need to actually generate the migration that will add these tables. But before we do that, let's add the user ID reference to the user table here in all of our other tables. So in the location table, we also want a user ID column. This will be an integer that is not null and references. And we'll grab the user table from our O schema and reference the ID column. And so I want a user ID on every one of these tables. So that way a user is associated with it and we can use O to make sure users only see their data. So we'll add this column to the location log. We'll bring in that user table. We'll also add it to the location log image. And then finally, we'll export all of these tables from Oth from our overall schema. So right here, I'm just going to say export star from our O table. All right, so we've installed better off. We've added the user ID relations to those existing tables. Now we need to generate the schema. So it's just going to work with Drizzle kit because this O schema here
is literally just Drizzle. So if we do a PNPM drizzle kit generate, that will generate the migrations. Let's take a look at it. So it created these tables. It then alters the other tables to add that user ID column as a reference. That looks great. Now let's spin up our database so we can run these migrations against the table. So then we'll do a bnpm drizzle kit migrate migrations applied and then we can pull up Drizzle Studio to see all of our newly created tables. Awesome. So we've got account session user verification. And then if we look at all of our existing tables, they now have a user ID column. So that's looking good. So we generated the schema. We also migrated the schema. Our office is set up. So now we're ready to implement login with GitHub, which we'll do in the next story. Now, just like I had to add all the environment variables for the preview deploy and for the lint job on GitHub actions, I'm going to have to do the same thing with all of these environment variables. So I'll go
through add these environment variables on both GitHub secrets and on Verscell push up make a pull request and move on to the next thing. Now when adding the better off secret to Verscell we do want this to be a secret value because if anybody knows that value they could use it to create fake signed cookies and we don't want that. So if you're on a Unix space machine you can actually use open SSL to generate random B 64 string that's of length 32. So I'll run this.
I'm going to run it again so you can't see my O secret. But if you run this locally, you'll get an off secret. That's what you should use on Verscell. And you don't want anyone to know this because and they could use that to sign fake cookies if they knew what that off secret was. Now, for the better off URL on Versell, we actually want this to use the preview deployment whenever we're in preview and then the production URL whenever we're in production. So here we're actually going to use a Verscell system environment variable. So there is a system environment variable called versel URL and we should be able to reference this with dollar sign Verscell URL. And so now whenever we deploy that under the hood is going to get set to the correct domain depending on where we deployed to. And we'll be able to check this in our next story when we're actually implementing GitHub OOTH because if we get redirected back to localhost 3000 when we're testing in production, we know we did something wrong there. But this should be the value we need. All right. Next up, we're going to set up GitHub OOTH. So, as a guest, I want to log in using my GitHub account so that I can access my
github oauth setup
personalized travel content. So, we'll set up Betteroth with a GitHub login integration. And whenever we click that login button on the homepage, it'll use that flow. So, if we head to the Betteroth docs, go to integrations and then check out Nux, we can add this API route. So, in NXT, all of our API routes are defined within the server folder. So in the Nux docs, if you go to guide and then click on directory structure, you'll see all the possible folders. But if you click on server, this is where your API endpoints will live. And so essentially what we're doing here is defining an API endpoint at API/ and then any route that begins with API/ is going to hit this handler and Better Off will take care of the rest.
Later on, we're going to be adding our own API endpoints for creating locations, updating, deleting, all that good stuff. And those endpoints are going to live in the API folder as well. So let's copy this code. Uh we'll make sure we're on the main branch. Check out a feature branch for ticket number 16. And then in the server folder, which already exists, we'll create a new folder called API. And then inside of there, we'll create a file called brackets dot do.ts. So inside of NX, the brackets represent there's going to be a param in the URL. And the dot dot dot is a catchall. So, like I mentioned earlier, anything that's API/off is going to get directed to this specific API handler.
Now, we'll update the import to our off config, which should be at lib/off. And that looks good. And now we'll set up GitHub ooth. So, inside of the better off settings, you can specify social providers. And in this case, we're just going to use GitHub OOTH. So, we'll head to lib/off.ts. And then in here, we'll specify social providers. Now we'll need to add our client ID and secret to our type safe env. So let's let's update that to pull it from env. But we will need to define these in our type safe env. So here we're also going to have our GitHub client ID, GitHub client secret. Both of these are strings.
Great. And then we'll import ENV to this file so it has access to it. And now we'll need to go create this client ID and secret. So if we head to the GitHub developer portal here and then click new ooth app, we can create one. For the name, I'm going to call this next travel log development. And this will be specific to development because I'm going to set the homepage URL to localhost 3000. And then we'll also need to create one for production. And we'll put our production URL in there. For the callback URL, you can see it should be specified like this.
API/callback/github. So we'll do that there and register the app. Now, this gives us our client ID. So, we'll throw that into our enenv like that. And then we'll need to generate a client secret. Now, this is a secret value. Don't let anybody see it. And then we put that value inside of our env. So, now that all of that is set up, we need to hook up the button on the homepage and in the navbar to call the client here with provider GitHub and then that will initiate the OOTH flow. So, if we head into pages and then index.view, view.
When I click this button, I want to sign in with GitHub. Also, if we're in components and then navbar, when I click this button, I want to log in with GitHub. So, because I don't want to duplicate logic, I'm going to create a component for this. So, directly inside the components folder, I'm going to create a component called OB button. And we'll grab that link there. We'll throw this into a template like so. And you might be wondering why I didn't put it in the app folder. I think the name off button is unique enough that we know that it's coming from our app instead of needing to call this app off button. So that's my logic there. You can follow the uh prefixing of your component names if you'd like, but we're just going to call this one off button. Now in this component, we need to use the better off client library. So I'm going to copy this codes here and in order to get some TypeScript inside of our view components, we can add that script with a laying of ts. We're also going to use script setup. We'll throw this codes in here. And then now we have our sign-in method. So we don't actually need to do anything with the return value because
this is actually going to redirect the user. So whenever this button is clicked, we actually just want to call that function there. So instead of a link, I'm going to change this to a button. And then we need to add a click event handler. So inside of Vue.js, the way you add event handlers is with the at sign. So if you do the at sign, you get access to all of the various DOM events. We care about the click event.
And when this button is clicked, we want to call sign in. Now, one more thing is after the user has been signed in, we want to redirect them to let's say slashdashboard. And that will be where all of our pages exist if you're a loggedin user. And so, one of the options you can pass in here is callback URL. And I'm going to set this to slash dashboard. So, now let's actually use this button in the navbar and on the homepage. So, if we head back to the navbar, instead of this, we actually want our off button. And I'll remind you, Nux uses autoimp imports, so it knows to find that in the components folder here. And then if we head back to our index page, we're going to use the O button right here. Now, let's start up the server and test it out. So, I actually have the dev DB running in the background. But if you remember earlier, we set up the dev task to start the DB and start next. So, if I do ppm rundev, that is going to use concurrently. So, that way our database is running in the background and it also spins up next.
So, now if I head back to localhost 3000, we can give it a shot. Will it work first try? Nice. We get redirected. So I will authorize it. Sweet. And then it redirects to /dashboard. So now we actually need to create the /dashboard route. So in pages, I'm going to create a folder called dashboard. I could just create dashboard.view, but all of the authenticated pages are going to live under this folder. So I'm going to put it in a folder. So we'll call this dashboard. And then inside of there, I'm going to create an index.view. And for now, this is just going to have an H1 that says you are logged in. Great. So now the dashboard page actually exists.
So when we click the button, the OOTH flow is initiated, but we should display a loading spinner just in case that redirection isn't immediate. So if we head back to the O button before we call the sign-in method, we're going to set a loading variable to true. So let's just create a new reactive variable. We'll call it loading. We'll use ref, which is built into view. It's a way of creating state. And we're going to default it to false. But right before signin, we'll set loading to true. And we have to use loading value because it is a ref. And then after login, we'll set it to false.
Now, this actually causes a redirect. So false would never get set, but at least the spinner will be there for a second before it actually redirects the user. And then now I want to show that loading spinner inside of the button. And I want to disable the button once they've clicked login. So here I'm going to say disabled is true if loading is true. And let's check out the Daisy UI docs because we should be able to find a nice loading spinner. Yeah. So one of these looks good. It's just a class of loading loading spinner and then we can define our size. Let's try medium. And what I'll do is if loading is in progress, show the spinner. Otherwise, show the GitHub icon. So, we'll put that loading spinner there. And then we'll have a v if. If loading is true, display that.
Otherwise, display the icon. Awesome. Now, just to test this out, I'm going to default loading to true so we can see what it looks like on the page. And this is what the button will look like when they're actually logging in. They won't be able to click again, and the loading state will be set to true there. Awesome. So, let's set this to false and then we will give this a try again. So, we don't have a logout method yet, but if we head over to storage, we can delete the cookie that was set and we should be able to try logging in again.
So, when I click this button, it happens so fast that you don't even see the loading spinner. But that's all right because if someone's on a slower connection, then they will see that loading spinner. So, that looks good to me. Now, we are redirecting to the dashboard after login. And we are showing that GitHub icon on the login button. Now, one more thing I want to do is I want to link the state between these two buttons because if we're on the homepage and I click login on this one, it sets it to disabled and shows a loading spinner. But we actually want that to happen on this button up here as well. And so for that, we'll actually create a store. So that way they're both reading from the same loading variable and they both can call the same O method. Now the way we define global stores inside of Vue is with a library called PA. Now in the Vue ecosystem, basically everyone is using PIA. There's there's not a bunch of state libraries and there's not some debates over what you should use. Everyone's using PA.
create auth store with pinia
They used to use VueX, but now Pia is the default. And Nux actually comes with a module called Pia Nux that will automatically set up Pa for us. And if we look in the Nux Pia docs, they do have a Nuxie command which will add that Pia module. So I'm going to kill the build for now and then we'll do a pnpm dlx of nuxy add pina and that should have updated our nux config to also add the pina module which it did and now we can define a store. So a store essentially has state and actions and then you can also have getters or computed properties. So our store is going to have the state of loading and it's going to have an action of login.
So that way both buttons can use that same state and action from this store. Now, in Nux, there is no convention about where to put your stores, but it makes sense to put them in a folder called stores. And that's what they're showing in this example here. So, I'm going to grab this example store, and in our app here, I'm going to create a new directory called stores. And inside of there, I'm going to create my O store.
So, we'll call this O.ts. So, I'll export use O store. We'll define a store called O store. And then for state, we're going to have loading. This defaults to false. And then for actions, we're going to have a signin action. And that's where we will handle the logic for signin. So now if I head back to my O button, I'll actually pull all of this out. So we have ourselves an O client.
I'll define it in here. And then our sign-in method is going to get moved to the actions. And I don't need that loading ref there. Now inside of our actions to access our state, we can just use this. So if I say this.loading, we can actually update the value. And then here I can also say this.loading equals that value. Now, this is kind of I'd say the the old way of defining stores where you have everything separate with your state and actions. We actually can define a store that uses all of the same composition functions that are used inside of view. So, I'm actually going to refactor this to use that instead.
So, we can actually pass a function into the argument of defined store here and then use composition functions inside of here. So, instead of having this separate state, we can literally just have a loading value that's a ref that defaults to false. And then instead of having to specify separate actions, we can just define this function called sign in. And what I like about this is you don't have to use this anymore. So now that this state variable is in scope, we can just use it the same way we would inside of a component. And so I actually do prefer this way of writing things. Now the way you expose stuff to the outside world is by returning an object and then putting each of the things you want to expose on there. So we actually want to expose loading and we want to expose that sign-in value. So you could define your stores either way.
I like doing it this way because we can use those same composition functions and because the return type of the store is automatically inferred. If you're doing it the other way and you need to do some custom things in your state, you might actually have to define a separate TypeScript type. It gets a little more clunky. So I prefer writing my stores this way. Okay. Now that we've put the logic here, we want to use this logic inside of our off button component. So over here instead of all of this, we're just going to grab the O store from use O store. Now I'm getting a TypeScript error because I need to run the build because the build is what generates those autoimp import types. So I'll do a PNPM run of dev. That should spin up next. It'll see that I've created that new store and it should give me access to it. Yeah. So you can see now the types are actually working here and we have access to offer. And now I can just reference those functions directly from ostore.loading and offstore.signin like so. And now to also see this in action. If I initialize
loading to true when we're on the homepage, both of those buttons will be spinning because they're both sharing that same state. And so this is the experience we want because if the user clicks this and it's taking a long time, this one earlier wouldn't have been disabled. But now they're both using the same state. Okay. So we'll set this back to false. We'll do a login. It's looking good. Now, lastly, we need to handle errors. So, for whatever reason, if the OOTH flow didn't work, we want to show the user a nice error. Now, built into better off is actually an error page.
auth error page
So, if something went wrong, it would take them to this page. But you can see it's not branded, right? It's just a built-in generic page. But we can specify our error call back and then tap into these query parameters and display it within our application. So whenever we call login, we can also specify an error callback URL. And I'm actually just going to define a new page called error. And so if any errors happen, they're going to hit that page, but it's going to have all of our navbar and color branding and everything else. So in pages, I'm going to create an error.
We'll add our template here. And inside of Daisy UI, they have a component called alert. And this is what we want to show the user because it looks like there's an error. Yeah. So we can get the one that looks nice and error-like. and we'll put the error as a message inside of there. Now I don't want to display that X image and here we'll say oh no and then specify the error. Now in order to get access to the error it's coming from the query parameters. So we'll add a script to this of type setup. Now in order to get access to the query params we can use the built-in use route hook. So I can grab the route from use route. This will give me all the information about the current route like the path, the hash and everything, but it also has the parsed query parameters there. So here I'll say error is route.query. Or if for whatever reason it wasn't defined or somebody got to this page without actually being redirected there, we'll just say uh an unnown error occurred. And this will
actually render that error out there. And so now if we head back to our app and then just go to slasherror, you'll see, oh no, an unknown error occurred. Now I want this to look a little bit nicer. So I'm actually going to wrap this alert in a card and then give it a bgbase of 300. And we'll also give this the container class and a margin top of four and also a min height of let's say 72. And set this to text center. And then we need to align the container to the center. So, we'll do a margin X of auto. Oh, and this should be min height 72. Yeah, I want to see a card that looks like that. Now, let's center everything and then also give them a button to go back to the homepage. So, right after the alert, I'm going to add a next link. We'll say home. And then we'll specify an icon and we'll use Tableau. I'm guessing they have an icon called home. We'll set that size to 32.
Now, this link just needs to go to the slash route. So, it'll take us back home. And we'll also make this a button. So, we'll give it the btn class. And then I'll give this a class of button primary. All right. Now, I want to add some spacing here. So, I am going to make this div a flexbox. Flex it in the column direction. Put everything in the center like so. I'll add a little bit of spacing for the button here. So, we'll just give this flexbox container gap of four. should push them apart. And instead of the home button, I think I just want like a back arrow. So, let's head to icons and see if we can find a nice little back arrow. Yeah, like this one. So, arrow left is the name that we need. All right, that looks good.
Lastly, I'm just going to increase the size of this alert. So, this alert will have a min width of let's say 50% or 1/2 and also text center. That looks much better. Okay. So, if an error happens, they'll get taken here. And if there was an error in the params like this, it shows up in the message and then they it takes them back home. Awesome. All right, that's it for this story. Next up, we'll actually show the fact that the user is logged in and show it in the navbar with their icon and stuff like that. But first, we'll commit it, push it, create a PR. You know the drill. And of course, I forgot we have more environment variables. So, I'm going to go through the same process to add these environment variables to Verscell and also our GitHub actions. But when I add them on Verscell, I'm going to create a new GitHub client ID in secret because that's what's going to be used whenever the app is running in production. Now, when you're creating the OOTH app for your production app, you're going to put the actual URL of your deployed versell app and the authorization callback URL is the same, just needs to be at that
github oauth production configuration
specific domain. Now, we specified that callback URL for our production URL, which means GitHub OOTH isn't going to work for our preview URLs. Now, there are ways around it and potentially we could have more consistent preview URLs generated for Versell. I'm not going to worry about that for now because I'm just one dev. We can test it on the the prod branch once it's been deployed.
Okay, we've hit a slight snag. Our environment variables on GitHub actions cannot start with GitHub_. So, I'm actually going to go through and rename those environment variables to Ocore. So, that way we can specify them inside of GitHub actions. Essentially inside of here, I'm actually going to rename this variable to O GitHub client ID and then this one to O client secret. And I am using F2 to rename the variable because that should automatically flow throughout my app. If we look back at O renaming of that variable just flowed through. This is one of the other nice things about using a type safe env. If you change the name in one spot, it'll change it all over your codebase so you don't have any hard-coded references to things that don't exist anymore. So now all I need to do is go into the versell settings and update those variables to have that prefix. Now we got that merged in. It's deployed. But if we want this to actually work, we do need a database in the cloud because now our GitHub ooth is trying to insert a user into that database. So we're going to go ahead and
set up Terso. If you head over to terso.te, you can sign up. And then within the dashboard, we can head to databases. So first we'll create a group. We'll call this the next travel log. And I'm going to put it in US West because that's closer to me. Great. And then within that group, I'm going to create a database. We'll call this travel log production. Now we'll create a token so we can actually connect to the database.
turso cloud setup
This is the token we'll use on Versell so it can talk to it. We want this to be readwrite and it will not expire. And then in the Verscell dashboard, we'll update the Terso off token to point to the token that was generated for us. And then for Terso database URL, we'll update it to point to the location of the database. So, we'll copy that URL, throw it in here, and save it. Now, we need to run our migrations against this production database. There are a lot of ways to do it. In an ideal world, especially if I'm working on a team and there are changes to the database every so often, we would want these migrations to run anytime before something gets merged into main. But, I don't plan on making any more changes to my database.
run db migrations on production
So, I'm actually just going to push these changes from my local dev. So, I'll actually update myv to point to the production instance of Terso. I'll run a DB migrate that'll actually migrate the database in the cloud and then my Verscell instance is ready to talk to that database and then after that in my local.env I'll replace it with the local settings so that way it's not pointed to production anymore. Now in order for these migrations to work I also set node ENV to production because if you remember earlier we set up our code so that if the ENV was development then it wouldn't use the off token. In this case we wanted to use the DB off token. So node env is set to production and it actually applies those migrations in the cloud. Now if you head back to the terso dashboard you can actually launch drizzle studio that's looking at your production database and you can see that all of these tables got created. So now whenever Verscell connects to this database it should be able to create users. I'm going to go back into myv and make sure that everything is pointing to development and local now because from here on out we won't need to push any
migrations to terso. Now to get forcell to pick up on those latest environment variables we are going to run a redeploy. And now with it redeployed with all the environment variables set, we should be able to log in with GitHub. Now it looks like Verscell isn't actually expanding this environment variable, I don't know what we need to do to get it to do that. But since we now aren't going to worry about preview deployments, we're just going to hardcode our deployed URL. Since this is the redirect URI that Better Off uses, and that needs to be the correct thing, or the OOTH flow will not work. We'll redeploy one more time and hope for the best. All right, moment of truth for real this time.
Now, I made a typo earlier. You might have made the same typo. In the authorization callback URL, make sure it's off/callback/github, not off/github/callback. I had that wrong and that was also causing a GitHub login issue. All right, with all that worked out, redeploy one more time. And it's definitely going to work or I'm going to fix it. I don't know. All right, moment of truth for real this time. Let's sign in with GitHub. That's what I like to see. Okay, so it redirected us to GitHub. We can authorize. We should get redirected back to the dashboard. We do.
Sweet. Now, if we head to the Turso dashboard and click on Drizzle Studio, we should be able to see that user in our database. And there I am. So, everything's hooked up, working. We can move on to the next feature. All right. Next up, we want to show the O status in the UI. So, right now, the signin with GitHub button just always stays there.
auth status display
But if a user is actually logged in, we should display their avatar and then also give them an option to log out and display the login button if they are logged out. So let's get back to the main branch, pull in all our latest changes, and then check out a branch for this one, which is number 17. Now here in the docs under the next integration session, you can see that we can create an O client instance. And in this case, they're actually importing from better off view. So our code was working before because we weren't doing anything specific, but we want to be able to use this composition function so that way we get a reactive session variable. So in my stores off.ts ts file we actually want to import from better off slash view and then inside of my store I can get access to the session so we'll grab the session here and this actually returns a ref meaning it's a reactive value so if the o client behind the scenes is refetching the session or refreshing it or the a logout event is
happening this variable is automatically going to get updated and we don't have to do anything special so we want to use that but we want to use the underlying data if we take a look at session It's a ref. So we do have to access dov valueue. And then on the value we have if there's an error we have whether or not it's pending, whether or not it's refetching. And then data itself has session and user on it. So we could try to return the entire session value here.
But you have to remember that this is a serverside rendered application and this is a pretty complex variable here. It also has some methods on it. So if we try doing that, we actually get a nuxed error that says it cannot stringify a function. So whenever you're returning any state here, you need to make sure that it's not some internal function or something like that. So in order to expose some of this data, we're actually going to use some computed values. So here I want to grab the user off of the session and I'm going to use computed.
And this will return session.value data user. And so this will give me access to the specific user. And this computed will automatically rerun if the session value changes. And so from here I can just directly expose that user object and then it's not trying to stringify all of the internal session functions. And if you look at user it either has a value because we are logged in or it's undefined. So this is what we'll use in the rest of our app. The other thing is instead of having our own loading variable we can actually tap into sessionispending or session.is reffetching. So right here we'll have another computed value and we can say session.value.ispending is pending or session.value is refetching. And now we don't have our own loading variable. But because we've exposed this loading variable, it's going to work the same way in the other parts of our app. So if the user is logging in, it'll spin. If it's updating the session data, it'll be loading. And because this is computed,
it's going to keep track of those values and update that value if it ever changes. So now that we have the user and this combined loading state available, we can actually use it inside of our O button. So over here now if the user exists we want to display an avatar image with a dropown where they can log out. So let's do that. If we head to the Tailwind docs they have a component called dropdown. And we want to use this. So there's a few different ways they do it. They have the details summary the popover API and then CSS focus. This one's the nicest because it doesn't require any JavaScript. It just has some HTML and it will automatically show that drop down. So this is the one that I want to use and it's nice and accessible. So it actually does work with the tab key. So this is what we'll use. We'll grab this codes. And here we'll display it. And so we only want to show this dropdown if the user exists.
So we'll say v if offstore do user has a value because user can either have the value or be undefined. So if we have a value for now let's just display the user's name. Say offstore. user name and then if the user doesn't exist, we'll show the sign-in button. So view has a built-in directive called v else which will show this if this is not true. The other thing we want is to listen for the loading state because if loading is true, we want to display the sign-in button because this will have that loading spinner there. So we'll say only display this dropdown if offstore.loading not loading is not true and a user exists. And so now if it's in a pending state, it'll actually say like sign in with GitHub and have the spinner and be disabled. But if we're actually logged in, it should display our name.
For the drop down, I just want this to say sign out. And we'll hook that up in a second. But let's see what we get. So if we head back to our app, it says CJ. And if we click it, we get a nice little drop down. So let's change the dropown location. If we look in their docs, we have positioning. So, we want this one, which aligns to the end of the button.
And the class we need is drop- down end. So, we'll throw that class right there. And now it's in a good spot. Now, I don't like that the color of this background is clashing with the overall background. So, this is using BGBAS 100. Let's use BGB 200. So, it's just a slightly different color. There's some differentiation between this and that.
So, that looks good. Now, let's actually show the user's avatar image. And Daisy also has a component called avatar, which just shows a nice image in a circle. So, we want avatar rounded. We're going to do this. And then to the left of the name, we'll actually display the user's image. Now, in order to bind this src attribute to the user's image property, we need to use a colon. And so the colon tells view that anything inside the double quotes here is actually an expression or reactive variable that we need to read the value of. So here we can pass in offstore user image. And it's possible that this image doesn't exist. At least that's how the typings exist inside of better off. So we actually will only display the avatar image if the user has an image. To be accessible, we'll also add an alt tag here. And the alt tag will just be bound to the user's name. So this will be ostore do user.name. All right, let's
see what that gives us. Cool. It's gigantic. So let's bring it down a bit. Uh we're using width 24. Let's try having it to width 12. Even less. Let's go like width 8. And yeah, that looks pretty good. Sweet. So we have the avatar and name displaying. Now let's work on that logout functionality so we can make sure that it doesn't display this if they're logged out. So when I click this, we want to sign out. For that, I'm just going to create a separate page that when a user goes to that page, it logs them out. So, let's create a page here called sign out.view.
sign out page
And we'll just give it a template here. We want to display a card with like a loading spinner, very similar to our error page. So, I'm actually going to copy this template and pull it in here. And instead of displaying all of this, we're just going to display a loading spinner. Going to copy that loading spinner from our off button. this. This is what we want. Throw it inside of this div. And let's grab a big one. So we'll do loading Excel. And this will always display if you're on the logout page.
Now when they visit this page, we actually want to call the logout method. So we'll pull in the off store like so. And then let's actually add a sign out method on the off store. So we'll grab another function sign out. And this will just call offclients sign out like so. And then we'll expose that method. And the main reason I'm wrapping it in my own function here is I don't want to run into that serializing issue where it tries to stringify the function. When we wrap it in our own function, NX is smart enough to know that it it shouldn't actually try to stringify that and it is an action. So now that we have that, we should be able to call it. And all I'm going to do is call it when this page is mounted. So I can use onmounted here we can say ostore sign out and so now the moment a user visits this page it will sign them out and the session data behind the scenes will get cleared out and because our offer is reactive user should then
be set to undefined after logging out. So now in this drop down here we actually want to link to the sign out page and for that we will use a next link and here we can just say this should go to slash sign out. All right so if we click it it takes us to sign out and it's loading osto.signout is not a function. That's not good. Um let's restart our dev server. We've we've done a lot so let's make sure everything is fresh. Head back here. We'll sign in with GitHub. Cool. We're signed in.
Let's try signing out. And that worked. So you can see the session data got updated. Now it's actually displaying this button. But what we need to do is if the user has signed out, we then want to redirect to the homepage. So in our store here after sign out is complete, we'll use the navigate method built into Next and say just go to the homepage.
And so now if we load this page, we sign out and then it redirects us to the homepage. So let's test the flow again. We can sign in. It displays our user there. We can sign out and then we get logged out. And so now the login button is showing when we're logged out. We're showing their avatar. We have a working login system. Great. And I actually got ahead of myself. I'm looking at the user stories now. And there is a story to log out. So dropown menu displayed with a logout option. Redirect to the landing page after logout. Logout option shows the logout icon. Okay, I'm getting ahead of myself. Now we've got two stories in progress. Let's actually go ahead and get this one done. We only have one more thing which is to add a log out icon. So if we head to icons, is there a sign out or log out or session? Log out. Yeah, something like this. This is the log out button. That's the one we want. So let's use that icon. And then in our off button on the sign out link, let's show
an icon. And the name is that. And we're going to make it pretty small. Let's do like 12. Let's see what that looks like. Okay, that's a little too small. Let's bump it up to 24. Yeah, that looks good. Um, honestly, it feels like that icon should be on the left of sign out. So, I'm just going to move it there. Yeah, that feels better. And now I can sign out. Great. Okay, we got two stories done all at once. Let me uh let me commit all of this, create a PR, make sure everything's working, and then we can test it on our deployed site. Now on this PR, we actually fixed two issues.
So I can reference both of those here. So this fixes number 17. I want my off status in the UI, but it also fixes number 18, which is I want to log out of the application. So let's create that PR and then we'll squash it in, merge it, and we're deployed. So let's test it out. We head to our app. There's some off state going on. It was cool to see the loading the loading spinner. So we are logged in already. Um let's try logging out. Yeah, that takes us here.
And then can I click login? Yes, we're here. Sweet. So it works in pro. For this next story, we're going to work on protecting routes. So as a guest, I want to be redirected to login when accessing protected routes. So if a user is not logged in and they try to go to slash dashboard, we want to redirect them to the homepage so that they can log in, pull in our latest changes, check out a branch for this issue, which is issue number 19, and then start it up. So in nux they have this idea of server middleware. Essentially we can define route handlers that will run before any requests to our app and we can do certain things. And so in this case we're going to check to see if the user is trying to visit /dashboard and they're not logged in redirect them to the homepage. So you can see the convention is to create a middleware in your server folder. So let's do just that. If we head to server, create a new folder called middleware. And inside of here let's create o.ts. TS. We will define our event handler and then we'll
protected routes redirect
make this an async method. And inside of here, we want to check to see if they're trying to get to the dashboard route. So here we'll say ifvent.path and I'm going to say starts with slash dashboard because we're going to have all of our protected routes underneath dashboard. And if you're trying to get there and you're not logged in, you should be redirected. So if they were trying to go somewhere, we want to grab their session data. Now in the Better Off documentation under the Nux integration, you can see that if we're in a server route, we can use this get session method to access the current session. So I'm going to do this here.
We'll import O from our lib directory. And now we can check to see if that session exists. And then if the session does not exist, we want to redirect that user back to the homepage. Now in the NuDox, they have this send redirect method that's available to us. So we'll do that right inside of here. So we'll say redirect back to the slash route. So that looks good. Now one thing to notice here is we're calling get session which is built into better off but we are passing in the event headers here because this code is going to run on the server side and we need the cookie for the user that's making this request and that exists on the incoming event. So that's why we're passing this in here because we're trying to get the session in the context of this request. So this looks good. Let's test it out. So let's go ahead and log out. And then now I am a logged out user. So if I try to go to /dashboard, it redirects us back to the homepage. Now on the homepage, we're using this same O button and we don't want to display their avatar on the homepage. So on the homepage, if they're
logged in, we'll actually just display a button to take them to the dashboard. So in this component, we need to get access to the off state. We'll grab the O store. And if OS store user does not have a value, then we're going to display the O button. Otherwise, we'll have a link that takes them to the dashboard. So, we'll grab the next link. We're going to send them to the dashboard. And here we'll just say start logging. And I want to make this a button. So, we'll give it a class of button and button primary. And then we'll display the next link if the user is defined. So, if I sign in, that takes me to the dashboard. But if I were a signed-in user that just went directly to the site, now they're going to see that start logging button and that takes them to the dashboard. So that looks good. Let's go ahead and commit, push, and merge it all in. So it's all merged in and deployed. If we try it out here, we can sign in with GitHub. That
redirects us to the dashboard. If we're on the homepage, we see that button to start logging. And then if we sign out and then try to go directly to the dashboard, we get redirected to the homepage. Next up, we actually want to do some work on SSR serverside rendering when we're dealing with the off session. So this ticket says the session is provided during SSR and a call to API offit session does not happen on the client after initial page load. So let's see how the app behaves right now. So if I I'm currently a logged in user. If I refresh, you'll notice that we see this call to get session which returns the user and the session data. And because we're using KNX, we can actually have this data available on the server side and not have to request it again on the client side. So if we take a look at the better off documentation here under the NX integration, you can see there's a section on SSR usage. And essentially what we can do is use this use session hook but pass in use fetch. So use fetch
SSR Auth Session
is a special hook provided by nux that will run on the server side provide that data during the initial render and then when this code runs again on the client side it won't refetch it if the data hasn't changed. So this is what we want to do now in order to set this up. We're going to have to reorganize our off store a little bit. So let's move this into in progress and then I'll go ahead and check out a branch with issue number 57. Now for you the issue number is probably going to be lower because I had to add this in afterwards but we're going to be working on this feature branch and then in the codes this is our off store and so right here we actually want to pass in use fetch but this in turn actually returns a promise so we need to await it. Now a pina store cannot be an async function. So we can't do this because then the pia store wouldn't be able to immediately provide this data here. So the way we're going to handle this is we're actually going to move this call into an init function.
So we'll have a function called init where we get that initial session data and then we'll call this init function from the top level component in this case our layout. If you take a look at the better off documentation they're calling this in index.view. So you want this to be the first thing that gets run so that way it retrieves the session and makes it available in every other piece of the app that needs that session data.
So we'll have this init function. it will be async but then we need a state value that we can update here that we can then depend on for the computed value here. So at the top here I'll create a session ref that is initially null and then inside of a init we'll just call this data and then once we've retrieved the session we can say session value is equal to data. Now in order for this to have the correct type we're going to have to do some TypeScript fu and essentially I want this ref to have the type equal to the return value of this once it's awaited. So the way we can handle that is we'll pass in our type argument here and we will say grab the return type which is a built-in helper in Typescript and we want the return type of this. So we'll say type of offclient use session. Now this returns a promise. So we want to get the resolved value. There's another helper built into Typescript called awaited and that will essentially unwrap that awaited value. And so now this will be the correct return value here. But we
need to also say that this can be null. So we'll say it's null initialize to null and then once we have the value set it on there. So this init function is going to be called once when the app starts up. And now we can actually use that session data inside of our computed here. So instead of this we'll say session.value.data dot user. And then this one gets a little bit simpler.
We'll say session.value is pending. Now let's make init available to the outside world so we can call it from the top level. So I'm going to expose init there. And now to call it, we're going to head over to our layouts. So inside of default view, this is where we're going to call the init function. And we're going to call it here because the layout is the first thing that renders and we want to get that session first before rendering any of our other pages. So we'll add a script in here language of Typescript and setup and then we'll grab the O store which is just use O store. And then we can call the init function. And so we'll say offtore.init like so. Now if we want to wait for all of the other pages to render, we actually will await this. And so this actually uses suspense which is a way of preventing everything else from rendering until this has resolved. And with this we should be good to go. So when the app initially renders it's going to call init that's going to run on the server. The server is going to retrieve that session and then make it available here inside of the store. And
then any other component that needs these values is going to have the latest computed value there. So let's try it out. If we refresh our dashboard here, let's clear the network. You'll notice there is no call to get session because when we rendered that page on the server, the session data was included. So it didn't need to make another request on the client side. And so this is the ideal behavior. Now there's one more issue and that is if we are logged out. So let's sign out and then refresh the page as a signed out user. you actually will see a call to get session.
And if you check the logs, there's actually this warning here that says use fetch must return a value. It should not be undefined or the request may be duplicated on the client side. And that's actually what's happening here. So this get session route is actually coming from better off. You see, it's a git request to API/off/get session. And if a user is not logged in, it actually responds with nothing or undefined. And this is an issue with nu's ability to be able to cache these requests because under the hood use fetch is using use async data and this needs a value to be returned because if not it's going to call that function again on the client side. Now there is an issue open in the better off repo that mentions this. So whenever you set up using use session in this way with use fetch you get that warning in the console that use async data must return a value. And I actually found a couple of ways to fix this. So like I mentioned, the main issue comes from the fact that git session returns nothing if the user isn't logged in. So
one way to fix this is to create our own custom use fetch. And so if you look in the Nux documentation, they show you how to do this. And essentially what I do have here is a request interceptor. So if we're making a request to o/get session and it was empty, meaning the user isn't logged in, it will actually respond with an object that has session null and data null. And that way use async data under the hood isn't getting an undefined value and won't try to request that data again on the client side. So this is one way to handle it.
But I found a better way to handle it which is just using O middleware. So built into better off is a way of adding hooks for all of these requests. And I have a simple little hook here that says if the request is coming to get session and the user is not logged in or the session doesn't exist, we're going to respond with this data instead of responding with undefined. Otherwise respond with the session. And what's nice about this is this just runs on the server side. We don't have any weird interceptor code in our client side code. This is actually going to change how git session responds for our NXT app when the user isn't logged in. If we check out the better off documentation, they talk about hooks. And this is one of the things I like about better off is how customizable it is in terms of tapping into before or after all of these various O events happen. And so this is actually how we'll solve it. So I'm going to grab this hook here and then inside of our off setup. So in lib off, we're going to add that hook right here. And create off middleware is built into better off. It comes from better off/plugins. So we'll import that at the
top here. Now because of this change here, we do need to update our middleware that we wrote earlier because the overall data returned from git session isn't undefined now. Now session or user is null. So if we head back to the middleware we defined instead of just saying does the session not exist we need to make sure we look for session do user so does the session user not exist to take into account the fact that it's getting an object with null properties instead of just undefined.
And so now on the server side if a request is made to get session and the user is not logged in instead of responding with undefined it's going to respond with this object here. And this actually fixes the issue of duplicating that request on the client side. So with this middleware added, if we head back here, let's clear the console and then refresh. Now you'll notice there is no request to get session. And if we look in the dev tools, there is no warning here. Let's actually clear it out to be completely sure. Start it up from scratch. But you'll see now if the request is made to the page and the user isn't logged in, we don't get the warning and we don't see that request to get session. And it should behave exactly the same if we are logged in. So let's go ahead and sign in with GitHub and that works just fine. But if I log out, you'll see that call to get session because that logout happens completely on the client side. It doesn't actually need to rerender the page. And so now locally that call to get session says, hey, that user is logged out and their session is null and their user is null.
So this is how we're going to implement it for now. I'm curious to see if the maintainers of better off have a solution for this. I'll link to this issue in the description because by the time this video comes out, maybe there's a better way to handle this. But for now, this should work fine. So now the session is provided when a serverside rendering is happening and the call to that get session endpoint doesn't happen on the client during initial page load.
So this looks good. I'll go ahead and add all of this, commit it, and push it up. Next up, we're going to show a sidebar in the dashboard. So as a user, I want to navigate the app with a sidebar so that I can easily access different sections of the app. So it will be a collapsible sidebar. So by default it'll look like this with all of our buttons to get to the various places and then we'll have a way to collapse it and then it will just show the icons instead. Now for this we want a smooth collapse animation and the collapse or expanded state should persist. So we're going to store that state inside of local stores. So if the user collapses the sidebar and they come back to the app, it'll stay collapsed. And then we'll have icons on all of the navigation items. So let's check out a branch. I am on the main branch.
create dashboard sidebar
Everything's up to date. We'll check out TL-20 and then we'll get to coding. So I want this sidebar to appear on the dashboard. So we're going to head to index.view here in the dashboard and then in here we'll have a top level element and then the sidebar will just be a div inside of that. Now there is a drawer component built into Daisy UI but I don't exactly want this to be a drawer because the drawer is on top of everything. I just want it to exist within that dashboard area. So this div right here will be the sidebar. And then let's give this a background base of 100. And then when it's open, we'll give it a width of 64. And then we want that top level chevron that can be used to collapse it. So we'll have a div inside of here that's going to have an icon.
And the name is going to be tabler. We want chevron left so that this button will collapse it like so. All right. So sidebar here. Let's increase the size of this chevron icon. So we'll give this a size of 42. That looks a little bit better. And then we want to push this all the way to the right. So we'll give the container a class of flex. And then we'll do justify content flex end. So justify end. And so now that chevron gets pushed to the end. Now I want the sidebar to be just a little bit more differentiated from the main area. So let's actually do bgbase 200. Should be a slightly different color. You can see it's a little bit darker. And now I want the sidebar to take up the full height of this area here. So for this, we'll actually head back to our layout. If we go to layout and then default, this is where our pages are getting rendered in.
So what I want is the navbar should always take up the top and then the main should take up the rest of the space. So our main container is already a flexbox with flex column. But if I give main a class of flex-1, that'll make it so that main takes up the whole bottom area. Let's look at the dev tools and make sure that that's the case. So, if we head to the inspector, we head to our app. We then have the navbar, which takes that up, and then we have main, which takes up the rest of the space.
Good. Now, I also want this main area to be a flexbox, so that way any page that's rendered inside of it can decide if it wants to take up the full area using flex one. So, we'll make this a flex box and then also flex it in the column direction. So, let's see what get that gives us so far. All right, so we've got our main element, our navbar, and then our main element there. Now we have this div which is going to be the sidebar and then eventually we'll have some area on the right which is going to render all the various pages. So we want to make sure that this which is a child of main takes up all of the space. So we're going to use a flex one on that one as well. So if we head to this page we'll give this a class of flex one. And so now this top level div takes up the whole space. And now we want this to take up all of the vertical space on the lefth hand side. So for that I'm going to make this container a flexbox as well. It's basically flex boxes all the way down. But if we make this a flexbox, now its child should fill the container just like that. And that's what I want
to see. And what's nice about that is now the parent is flex row. So I can actually have another element here which will be the main content that we're going to put on the right hand side. So eventually that will have the map or whatever other page we're looking at. And I can give this one a class of flex one. And that will take up the remaining space on the right hand side. So just to see it right now, let's just do a a bg of like yellow. and you'll see that it's taking up the full right hand side.
Yeah. So, this is what I want. So, essentially our sidebar always exists on the left, takes up the full height, and then we can start rendering pages into this yellow area here. So, I'll remove that yellow background for now, and we can work on the navbar here. So, now let's list all of our buttons below this collapsible area here. So, let's create a div. This will be the wrapper. We're going to make this a flexbox. We'll flex it in the column direction and give it a gap around each of the buttons. We'll give it a gap of two. And then inside of there, I'll add a button. In this case, we'll do a next link. And if we look back at the wireframes, this should say locations and should have an icon on it.
So, we'll say locations. Let's bring in an icon. We'll set the name here to tabler map and give it a size of let's say 24. So, that looks all right. Let's turn this into a button. So, that gives us some nice default styles. And now it's nice and clickable. But let's actually shift the text over to the lefth hand side because if we look at the wireframes, it's all left aligned. So on that button, believe a button is a flexbox by default. So we should be able to say justify start and that pushes it to the left. Yeah. So that looks good. We've got a nice little locations button. Let's add another one for add location. So we'll have another next link right below it. But this one will say add location. And we want a plus icon. So if we look at it, that's looking good. Um, I do want like a filledin plus sign. So, let's head to icons and search for a plus. Let's see what they have. I like this one. So, this is circle plus filled. Throw that in there. So, that's looking better. And
then from the wireframes, we also want a divider here. In Daisy UI, they do have a divider that looks like this. And it's literally just a div with class of divider. So, let's add that here. Dives divider. So below the icons, yeah, we have a nice little line. And then below that, we want to show a log out button.
So we'll grab another Nux link. And this one's going to go to the sign out page. And this will say sign out. We want that sign out icon. We should use the same one that we used for our O button. This logout-2, that's the one we want that. So I actually don't like what these buttons look like here. I think we're just going to add our own styles instead of using a default button. You could use a button, but that adds some some extra styling here that I don't exactly want.
So, let's do this. If we instead say that this is a flexbox with justify start. See what that'll do. Yep. And then give it a gap of two. That's a little bit better. And then we want it to be pushed a little bit from the left. So, let's add some padding to. It's looking better. And then we want some hover state. So, when the element is hovered, let's do a bg base of let's try 300. Yeah. So that's nice and hoverable.
And whenever we're hovering, we'll do cursor pointer. So that way people know that they can click on it. I like that. So it's not like a completely separated button. And so now I want to reuse these styles on these other buttons. So I'm actually just going to extract this out into a component so I don't have to copy paste all of these classes on each of these. So in our components folder, let's actually create a sidebar button view and pull all of that into here. So we'll have our template. inside of our template will be a nux link and then we can define some props. So I want to pass down the label and then also pass down the icon that should be specified here.
So we'll create our script language of ts and setup and then inside of here we can define some props. So in view there is a built-in function called define props and this allows us to receive data into this component and then to specify the types we can pass this in as a generic here. So we can say we're expecting a label which is a string and then we're expecting an icon which is also a string like that. And now we can use these props down here. So right here we should render out props.l and then here we should render out props icon like so. And so now this component is nice and reusable. So if we head back to the dashboard right here I want a sidebar button. The label is going to be locations and the icon is going to be tabler map like so. And if we did everything right, it should look exactly the same. It does. Nice. And now we can we can reuse that for our other ones. So
here this will be add location. And we'll set this with circle plus filled. And then we have our divider. And then we have another sidebar button with the label of sign out and an icon of log out too. Now, we're going to need one more prop, which is the href that we're passing into two. So, this one should have an href of slashdashboard. And then add location will be dashboard slash add should be the URL.
We'll change it later on if we think it's something different. And then this one should have an href of slash sign out. But now we need to make sure that this component accepts href as a prop as well. So, if we head back to sidebar button, we also need a prop of href which is a string. And then we can pass that into the two prop here. So two is props.href like so. Now all of these look consistent and they should take us to those places. So yeah, add doesn't exist. Sign out signs us out which is good. And then locations takes us to exactly where we are. So I'm pretty happy with this. I actually don't like the gap that the container is adding. If we head back over to the dashboard, this has a gap of two, but each of our buttons already have padding. So, if we remove that gap, let's see how it looks.
Yeah, I like this a little bit better. Now, the buttons are a little bit more consolidated. I like that. Now, another thing I want is if you're on the page that this thing links to, it should actually be a slightly different background color. So, this one, for instance, should be a different background color because we're on the dashboard and it links to dashboard. So, inside of our sidebar button component, we can get access to the current path using use route. So, we can grab the route from use route and then route.path path is going to have what the current path is. So we can add a conditional class on this next link here. So we can say we're going to bind to the class attribute and then specifically we want to add a different background color. So let's add bgbase 200 like this if the route.path is equal to the props.href like this. So that looks good. But I am realizing that the background color of the sidebar is BGBAS 200. So if we set this to VGBS 100, you
can see that it's a little bit lighter. If not, I think I'm going to swap this. So if we head back to the dashboard, I think I'll make this BG base of 100. And then if the button is active, we'll make it a BG base of 200. So that way it's a little dark. So yeah, I like this better. We'll have it has this lighter color. Eventually there's going to be stuff on the right hand side, so it'll be nice and differentiated. But if we are actively on one of these things, then it will highlight. But now let's make this thing actually collapse cuz right now it's always expanded. So we head back to the dashboard. We're going to need some state inside of here.
collapsible sidebar
Essentially just have a is sidebar toggled. It's going to be true or false. If it's false, we show it like this. But if it's true, we'll show it in a collapsed state. So we'll add a script here. Make it set up. And then we'll just have a state variable is sidebar open. And we'll default to true. So now I want to change the width of this sidebar based on this value here and we'll do a class binding for that. So we'll bind to the class and we want to apply the w-64 class if is sidebar open is true. Otherwise we'll apply a smaller width. So let's try like width 16 if is sidebar open is not true. And then now whenever we click on this element here this should toggle is sidebar open. So let's add a click event listener here.
And whenever we click it, we'll say is sidebar open is the reverse of it. So just like that, we should get a nice and collapsed sidebar. Cool. We have some more things to fix, but the sidebar is collapsing. Now another thing is when the sidebar collapses, we actually want this chevron to be in the center. So we can style that as well. And right here, this is doing justify end. But if sidebar is collapsed, we want to do justify center. So we'll also add a class binding here. And we want to apply justify center if sidebar open is not true. And then we'll also pull out justify end and only apply it if sidebar is open. So justify end if is sidebar open. Okay. Now with that, when we collapse, it should be in the center, which is good. And then we can expand it. Nice. Uh, let's also add like a cursor and hover state to this area here. So, this should have a cursor
pointer when you hover over it. And also, whenever you hover over it, we'll do a background base of 200. So, looks nice and clickable. When I click it, it expands. When I click it, it unexpands. So, let's actually change the icon when it's collapsed. So, when it's collapsed, we want the chevron to point to the right. So, for that, we'll use a v if statement. So if the sidebar is open, then we're going to display chevron left. Otherwise, we're going to display chevron right. So now that should swap out the the icon depending on the state.
So collapse, expand, collapse, expand. Very good. Now, when we're in the collapsed state, we only want to show the icons for all of these buttons. So if we look at the wireframes, you can see when we're collapsed, it doesn't show the text. It just shows the icons. So let's handle that. And essentially what I want to do is pass down is sidebar open to all of these buttons.
And then the buttons can decide how they want to render. So let's actually define a prompt called show label. So we only want to show the label if is sidebar open is true. And we want this to be the case for all of these buttons. And so now in the sidebar button, we'll take in another prop which is show label. And this is going to be a boolean. And if this is false, we do not want to render this label here. So I'm actually going to wrap the label in a span so I can hide it and show it. And we only want to show this if show label is true. And then we can throw the text inside of there. So now when we're in the collapsed state, it hides the label.
That's exactly what we want. Sweet. Now another thing is when we're in the collapsed state, these should send their icon to the center. So let's do that. So we're going to add another class binding here. that says we want to apply justify center if show label is false. And then we only apply justify start if show label is true. So we'll say justify start is if show label is true. And just like that, they're in the center. So when we're expanded, it's nice and big.
And then when it's collapsed, the icons are in the center. Now, whenever the sidebar is collapsed, I actually want an indicator of what these buttons do because icons might not always be the best indication of what they do. So, we actually should have some tool tips here. So, when it's open, we can see the labels. We know exactly what they do. But when it's collapsed, we want to see a tool tip when we hover over them, so we know what we're getting into if we click on that specific button. Now, Daisy does have a tool tip component built in. Let's check it out. And you can see on hover, it shows the tool tip.
And we want to show our tool tip off to the right like this because it'll appear to the right of the sidebar. So let's grab this. And then we're going to wrap this link in our tool tip component. So right here is where the element will go. And then data-tip is how we specify what should appear inside of there. But we only want the tool tip to appear if show label is false. So let's actually bind this and set it to if show label then don't show any tool tip otherwise show props.label as the tool tip. And right now toolt tip open makes it so it's open all the time. But let's just see what this gives us. If we head back over.
Yeah, you can see we have a nice tool tip for each one of these. But if we remove tool tip open then it will only appear on hover. So on hover you get these nice little tool tips and then when we expand we don't get the tool tips but we are getting that little element to appear there. So I think we'll have to add another conditional class. So we likely only want to apply the tool tip class if show label is false. So here I'm going to add a class binding that says apply the tool tip class if show label is false and then remove the tool tip class by default.
Now yeah. So now when it's expanded, we don't see those tool tips, but if it's collapsed, we do see the tool tips. Nice. Now, one last thing is we want this to animate. Right now, it's just opening and closing. It's It's pretty jarring, but if we look at our issue here, it says with a smooth animation.
So, let's actually just add a width animation on the navbar element here. So, that way it will animate the changing of the width instead of just changing immediately. So back in the dashboard on our sidebar element here, let's give it a transition all. So that will transition the height and then we can set the transition duration with duration. And then let's do 300. So it will change the height over 300 milliseconds. And so now if we collapse, it's a nice little animation. And if we expand, that looks good, too. Now there's a few more things we need to fix here. You'll notice when we collapse, the text instantly disappears. It actually looks all right. It's not super jarring, but when we expand, you'll see that the icon disappears for a second and the text is like immediately visible. So, we actually want the text to transition in and out. So, that way it looks a little bit smoother whenever we're expanding and collapsing. So, built into Vue.js is a component called transition. And this allows you to wrap an element that will potentially be
removed or added to the page. And you can specify what transition you want to use. So you'll see here this paragraph tag is only displayed if show is true. They wrap it in transition and then you can specify a CSS class which will determine what that transition will be. So here whenever we're entering or leaving we're going to change the opacity over.5 seconds and then when the element is no longer on the page the opacity will be zero. So we want to do something very similar. So, inside of our sidebar button, we're actually going to wrap this label here in a transition. And then, instead of changing the opacity, I actually want to change the size. I want it to grow and shrink. So, if you look down below, they actually have an example of some custom CSS animations. So, here we can give it the name. And then in our CSS, we need name interactive and then name leave active. And then we can specify any CSS that we want. So let's actually create a shrink animation so that it will scale up and then scale back down whenever
it's being expanded and collapsed. So we'll copy this. So here we'll actually call our animation grow because we'll grow it and shrink it using the transform property. And then down below we'll add a style tag. We'll make this scoped so it only applies to this component. And then we'll modify our class here. So I want this to be grow interactive and then grow leave active.
And then we'll create some key frames that grow it. So it'll go from zero to one. And we don't want that bounce effect. We just want it to grow to its actual size. So that looks good. And then now we'll change this to use our grow animation. So grow over half a second. And then when you leave, grow in reverse. So it'll shrink. Now I want this transition to match the transition of the sidebar. And if you remember, we set that duration to 300 milliseconds.
So let's set this to.3. And so now that text should grow and then shrink whenever we expand or collapse the sidebar. Let's try it out. So now you can see if we collapse it shrinks the text. And then if we expand it grows the text. So that's a little bit nicer. It is a little bit jarring though because whenever we collapse it takes too long for the icon to pop up. So I actually want this animation to be a little bit quicker than the sidebar itself. Let's actually set it to 0.2. So now it'll have fully shrunk before the sidebar is fully collapsed. So that's a little bit better. Let's try even like 0.1. So now when we collapse it's a little less jarring. So this looks good. I think one of the other thing that's happening is whenever the sidebar gets small enough the icons actually shrink a little bit.
It's like their default behavior. And during that transition, the text actually will potentially wrap to the next line. So, let's at least add on our sidebar button this flex container here, which flex the icon and the text. We actually want to make sure that this does not wrap so that way it stays all on one line. See if that's helps us a little bit. So, that's a little bit better. And this is good enough for me. I think if you can come up with better transitions for this, definitely let me know down in the comments how you got this working.
But, I'm pretty happy with what we have here. Now, lastly, this chevron is bothering me a little I think it's a little too large. I think we set the size of the chevron to 42. Yeah, let's bring this down to 32. I like that better. And then the collapsed size should be 32 as well. But now that it's smaller, I do want to increase the padding. So, let's increase the padding, let's say, by two on that element. Much nicer. I like this. Yeah, that's looking good. Okay, if we head back to our issue, we've got a nice smooth animation when we collapse it. We also have icons on all of the navigation items. But now we want to persist that state. So if I collapse the sidebar and then I refresh the page, it's always expanded. We should store the state of the sidebar in local storage. So if we head back to our dashboard here, whenever we click the collapse button, we want to store that state in local storage. So right now, we just have this click handler right on the element. Let's actually put this into a function. So let's just call this
persist sidebar collapse in localStorage
toggle sidebar, like so. And then in our script, we'll have a function toggle sidebar. This will have the same logic, but since we're writing it in our script, we will have to say ref.AL equals ref.value. But here, because this function is getting called every time we toggle it, we can store the current state in local storage. So when they click the button, we're going to say local storage set item, and we'll set is sidebar open to be the current value, like so. Uh, TypeScript does want us to turn this into a string, so we'll do that. And then let's see what happens in local storage whenever we press this button. So if we head to storage here in the dev tools and then local storage when I collapse it sets is sidebar open to false and then when I expand it it sets it to true. So now we just need to read from that value when this component mounts. So built into view components is this onmounted hook. We can tap into this and we can say when the component is mounted set is sidebar open to that
value from local storage. And the main reason I'm not just passing in a read from local storage right here is because this code actually runs on the server side. And then on the client side once it's mounted it has access to local storage. So here we'll say is sidebar open.value is equal to local storage.get item. We want to grab is sidebar open and we want to say if that is equal to true like so. So now if we refresh the page that looks good but if we collapse and then refresh the page the moment the page loads it collapses the sidebar. Now the way this is written right now we're always going to see that slight bit of time before it actually collapsed when you initially load the page. And that's because the page itself is being rendered without the sidebar being collapsed. and then when it loads on the client side, we're reading that value from local storage and then collapsing it. Now, one way to fix this is to store that sidebar state in a database, right?
You could maybe have like a settings table and when a user collapses the sidebar, store that setting there and then that way whenever you're rendering this page on the server side, you don't have to read from local storage. You can actually get the current user's settings and then server side render it with the sidebar collapsed. I'm not going to do that because this is perfectly fine for me. But you will notice that slight bit of time before it collapses because it has to read from local storage. All right, so we now have a persistent collapsed and expanded state. So this looks good to me. Let's commit it, push it, merge it, and move on to the next thing. Next up, we're going to allow the user to create new locations. So as a traveler, I want to create new locations with detailed information so that I can document places I visited or plan to visit. So we're going to have this add location page. It'll have the form where they can put the place that they visited, give it a description, and then for right now, we're just going to have them manually type in latitude and longitude. Later on, once we get the map set up, we'll make it so that they can click on the map to automatically set latitude and longitude. But for now, we
dashboard nested routes
just want to start getting stuff into the database. So, we're going to have a simple form. Now, you'll notice with this layout, this location form renders on the right hand side in this main area and the sidebar is still visible. So, we're actually going to do some nested routing. So in next for nested routes, you can actually have a folder that has the same name as a page file and then any component inside of there can get rendered into an outlet in the parent.
So we're going to restructure things slightly so that our dashboard will be dashboard.view and then we can have a page like add view and then render that in to the right hand side in the dashboard. Let's go ahead and check out a feature branch. This is issue number 21. And then we will rename this dashboard file to dashboard.view. Move it into the root of pages. And then inside of the dashboard folder, let's create a new component called add do.view. And we'll just add a simple template for now. Just says add location. Now, in order to get this to render on the right hand side in the dashboard, if you head to the dashboard component, this area right here with this flex-1, this is where we want to render it in. So, right inside of here, we will add a next page like so. And right now, our ad location is going to be at dashboard/ad. So, when we head to dashboard/add, it will see that dashboard has a nested route here and
render it on the right hand side. And so, by default, there's nothing when we're on / dashboard. But if we head to add location, you'll see that it renders that component on the right hand side here. So, first, let's go ahead and push it to the center. Give it some max width. Add the title and the description. So in our add page, I'm going to have a top level container div.
create location form
And we'll give this a class of container which comes from Tailwind. And we're going to give this a max width of medium like so. And we'll also do margin auto so it's nice and centered. And give it a little bit of padding so it's pushed down a little bit from the top. We'll also add some margin top so it's a little bit pushed down from the navbar.
And then we'll put our title inside of here. And no need to yell. This will just say add location. And then we'll add the description below that. But let's go ahead and wrap this in its own container. So that way we can separate it from the form a little bit. So we'll have this here. Let's give this a class of text large. And then we'll have a paragraph tag. Give this a class of text small. And then add our description in there. See what that gives us. It's looking good. So a location is a place you have traveled or will travel to. It can be a city, country, state, or point of interest. You can add specific times you visited this location after adding it. So that's nice and descriptive. Now we want to go ahead and add the form. So if we head over to Daisy UI, they have an input field and this is what we're going to want. And for Daisy, it's pretty simple. You just give it a class of input and it will show up in the right way. So below this div with the title in it, we're going to create a form. And inside of there, we'll have our input. We'll give it a name of name.
And I'm not going to put a placeholder. Let's see what we get. Let's make sure that all of our inputs are full width. So we'll give this also a class of width full. And then let's also separate these two. So instead of putting margin top four on the whole container, let's actually just give this a margin Y of four. So it has margin top and bottom.
And that way it'll separate it a little bit from the form. Yeah, that looks much better. Now, we also want a label on this form so they know it's the name input. So here we can see we can add a label like this. So it's a field set with a legend. And then you can also add some help text if you'd like. So that's going to look like this. Pull that in here. And this should just say name. And we'll hide this field set label for now, but we will use it later because we're actually going to display any validation messages right below the input. So we'll hold on to that so we don't forget about it. So that's looking good. Next up, we also want the description. And that's going to be a text area. So if we look in Daisy, they do have a text area and it's very similar. Just give a text area a class of text area. So we'll do a very similar thing with a field set. We'll call it description and then instead of an input, we'll give it a text area.
Close that out and then give it a class of text area. And the name here is description. So that's looking good as well. And then finally, we have the latitude and longitude. So those will just be inputs with type of number. So here we'll say latitude name is lat because in our database it's called lat.
And then we'll have one more of these and this will be longitude. So long like that. Yep, it's looking good. Let's give these a type of number instead. So and then we need a submit button. So at the bottom of the form, I'm going to create a section here so I can push the buttons to the right. We'll have a button that is of type submit. And this will say add. And we'll give it a class of button. And we'll say button primary like so. And then we'll add the add icon. I want this to use the same icon as the sidebar. So we'll do this circle plus filled like so. And then give this a size of 24. So that's looking good.
Like I said, I want to push these buttons to the right. So we're going to give the container a class of flex. And then we'll do justify end. So it pushes it to the right. And then we also need a cancel button. So we'll add this. It will not be of type submit. So we'll say cancel. And then we want to show the back arrow here. If you remember on our error page, we did use an arrow left.
Yeah. So that is the icon that I want to use here. And we'll pop it in here. See? Yep. But I want to put that icon on the left. And then we want a little bit of spacing between these two buttons. So let's give their container a gap of two. I like that. And then let's make the form a flexbox as well, just so we have consistent spacing between everything.
So on the form, we'll give this flex flex column. And then we'll give this a gap of two. Yeah. So I like that. Now there's spacing between each input and a little bit of spacing between the buttons. I want this button to be gray. So let's go check out the daisy button options. Yeah. Now, I'm thinking maybe we do an outline button. So, this is just btn outline. So, we'll add that to the cancel button. Like so. Yeah, I like that. Cool. And this cancel button is behaving as a submit button. So, I'm going to give this a type of button just to make sure that it does not submit the form. And let's refresh. Yeah. So, that button shouldn't submit the form. This button should submit the form. And we're going to handle that with JavaScript in just a second. Okay. So, the form's looking good. Let's head back to our checklist. So, we're accepting all of the items, but now we need to do some validation. So, before submission, we want to make sure that all of the required fields are filled in. And then we're also going to do some validation of the coordinates to make sure that
validate form with vee-validate
they're valid latitudes and longitudes. So, if you head to the Nux documentation, go to integration and then modules. Honestly, it looks like they've updated their site since I started making this video. It looks slightly different than last time. I don't know what changed, but if you search for validate, validate is one of the most popular libraries in the Vue ecosystem for validating forms. So that's what we're going to use and it actually integrates with Zod. So we can get a ZOD schema based on our Drizzle config and use it to actually validate the form. So to add it, we can run PNPM add like so. And then we'll add it to our next config. So here under modules, we'll also add the validate next. Now to use it, they provide a use form hook. So we'll add a script to our add page component. Make sure it's a script setup. And then here we can grab the form and we can say use form. So you can see it's autoimp imported here. And this exposes a couple of things. One thing
we'll need is their handle submit function. This will get called if all of the fields are valid. And then part of the options we can pass in here, we can provide the validation schema. and they provide a utility function called twotyped schema and they accept a lot of different schema types but of course they accept zod. So we need a zod schema for our location here. Now because we're using drizzle we can actually use a library called drizzle zod that automatically gives us a zod schema based on our database table schema. So if we head to our schema and then take a look at the location table, we can use drizzle zod to instantly turn this into a zod schema. So if you head to the drizzle docs, you can see we can add drizzle zod. So we'll do that and then from there we can use this create select schema and then also create insert schema and pass in the table. So right now we just need the insert schema because we're putting stuff into the database. So drizzle zod provides the
drizzle zod validation schema
create insert schema method. And then here we can export the insert location schema and set that equal to create insert schema. and then pass in the table. Now, just like that, we have ourselves a Zahad validator. Now, by default, it includes all of the columns, but whenever a user is inserting data, they shouldn't include the ID cuz that's going to be automatically added by the database. We're also going to generate the slug on the server side. So, we don't want to include that. And user ID, created at, updated at, all of that's going to be handled on the server side when we're actually putting this into the database. So we need a schema that only includes the fields that the user is actually typing into the form. And for that we can actually just use the omit method built into zod schemas to remove some of those fields that we don't want to validate against. So here we're going to omit ID. We'll also omit slug and then we'll omit user ID and created at and updated at. So now this
schema will only validate name, description, latitude, and longitude. And then everything else is going to be handled on the server side when we're actually putting it into the database. One of the other things we can do here is add some length limit validation on the name and the description. And that can be passed in via some options here.
So here we can specify any of our fields and then we give it a callback function that accepts the field validator and then we can further modify it. So you can see field is already a string validator but for instance we could set the min length to one. So that makes sure that it can't be empty. And then for the name we could also set a max length. Let's set a max length of 100 for the name. And so now when we're using this validator it'll make sure that it's within those constraints. We can do the same thing for description.
So we'll add it here. And description is optional. So we won't set a men length. But let's set a max length of a th00and for that description. Now, if we look back at our user story, we also need to validate the coordinates within specific ranges. So, we can do that with min and max as well. So, if we take a look at lat, we'll grab the field, and then we can set a min, which we'll have to look up, and a max. And then we can do the same thing for long. So, I looked this up. I found this website that lets us know that the ranges for latitude are 90 and positive 90. And the ranges for longitude are negative 180 and positive 180. So for lat the minimum is90 and the max is 90 and then for longitude 180 and max is 180. So now whenever we are validating against this we're going to make sure it's within that range. So now let's import this schema in our form and pass it in to this validation schema. So
for this we can use a method called twotyped schema and then we'll pass in our insert location schema. Now in order to get access to two typed schema we need to install the zod sub library of v validate. If you check out their docs you can see we can add this validate/zod library. So we'll add that and that will give us access to this twotyped schema method like so. and then we'll be sure to pull this in from our database schema. Now, in order for this form to actually tap into that validation, we need to use these components that are provided by Validate. So, there's capital F form and then there is capital F field. So, instead of just using a regular HTML form and input or text area, we'll use these instead. So, down below, we'll change this to capital F form. If we hover over it, we should see that autoimp import is working. And then for each of our inputs, we want this to use
capital F field like so. And then we'll need to do the same thing for our text area. And for the description, we should give this a type of text area. So if we head back to our form to the ad page, it's still rendering out, which looks good. And now we need to tap into the submit event so we can actually handle that validation. So on the form here, we can use the at sign to tap into a DOM event. We specifically care about the submit event and we are going to create a method called onsubmit and onsubmit will be a wrapper of handle sububmit. So we'll say onsubmit is handle sububmit and then we can pass in our callback here that takes in the values that were submitted by the form. And you can see if the form is validated it's going to be an object that has description, name, latitude and longitude. So for now we will log this out. Now I'm realizing in order to use this custom hook here, we actually should use the lowercase form like so. And then that allows us to
handle location form submit / show validation errors
handle everything with JavaScript here. So another thing we want to do is prevent the default action. Built into view are helpers on DOM methods. So right here if I doprevent that will prevent the default action and then call this onsubmit function here. Now if we want to see any validation errors, we can get access to them from this hook here. So you can see we also get access to errors. And for now I just want to see them in the console if there are any errors. So temporarily I'm going to create an effect that will run anytime the errors change. So we're just going to log the errors. We'll do errors. And because this is a ref, we can use a helper built into view called to raw. And that will make sure that we just see a plain object in the console.
So this is just temporary. So we can make sure that this validation is actually working. Let's give it a try. So let's open up the dev tools. You can see that there are no errors right now. But if I try submitting, you can see that the name is required and latitude and longitude is required. So these errors are actually coming through. Now we want to display them on the form itself. So this field set label that we commented out earlier, we're actually going to use this. So we will say only display this field set label here if there's an error in this case for the name field. So here I can say v if errors dot name. So if this exists we're going to display that error right here like so. And we'll do that same thing for all of the others as well. So for description we'll say if errors.escription. If you remember the only error that will happen with a description is if it's over 1,000 characters but we still want to let them know that if that's the case. and then we'll add for latitude and longitude. So with all of that now when we submit we
should see those errors listed out below. Now I also want to show like a red border around the input here. So let's take a look at Daisy UI. We'll head back to their input documentation and we can specify a color. So yeah, if we do error on the input and see input- error, it will show up as red. So we want to conditionally apply the input error class if that field is not valid.
So on the field here we'll add a class binding and we'll say please my friend apply the input error class if errors.name has a value and we'll do the same thing for all of the other inputs as well. Now you can probably fill a refactor coming. We could create our own form component that handles all of this so we don't have to duplicate logic. Let's get it working first and then we are going to do a refactor. So here this will say errors.escription and then we'll add it for lat and long as well. Okay. So now if I submit they're nice and red and then I want this text here to be red as well. So on this element here let's add a text error. So this is built into Daisy UI. It'll give it that nice red color and match the input. So with that now when I submit we get some nice error messages and if we make them valid so let's say I'm adding San Francisco and add a description you'll notice that the
moment I tab out it automatically validates it because the default functionality of the validate library is to validate on blur and so I can set this to something like 40 and 110 and it's valid but these should validate for ranges as well. So if I do like 100 here, number must be greater than or equal to90. And if we try like 100, number must be less than or equal to 90.
So that's looking good. Now we would expect if everything's valid, when I submit, we should see the validated object there. And we do. There it is. So we've got the description, latitude, longitude, and name. So now at this point, I want to do a refactor. So as you can see, we have a lot of duplicate logic here, right? We're showing the error. if there's an error. We are adding the input error class on the input if there's an error. So, I'm going to pull this into a separate component and clean up the logic in this component. While we're here, let's go ahead and remove those error logs because we know that's working. And then in my components folder, let's create a new component. We'll put it in the app directory. So, we know this is our component because it's I'm going to call it form field, but I want to know that this is from my application. So, we're going to call this app form field.view.
re-factor form field component
Give it a template. And then we'll pull that default logic and turn it all into props. So we want this to be a field set like so. And then for props, we need to just take in an error message. So the error message will either be a string or undefined. So we'll add our script lang ts with type setup. And then we'll have our props. So we can use that define props macro. And the type here is just going to be error. And this is a string but it is optional because initially error will be undefined. And then everywhere I have errors.name that will instead be props. So if the error exists add the input error class and then also show the error. The other prop we want is the label. So this will be required.
We'll make this a string. And then we can pull in props. Right here. And then we also want to take in the name of the input. That also is going to be required. and it's a string. So here we'll bind name to props.name. And then we'll also take in the type because it can either be text or text area. So here type, we're actually just going to make this a string union. So it can either be text or text area like so. And then we'll use that type right here. Now we also need to conditionally apply either the input class or the text area class depending on the type. So we'll add that here. But while I'm thinking about this, we should add some auto formatting for lots of attributes, right? Because I actually want this to wrap to the next line. It's really hard to read if I keep typing them out here. So, we'll do that with ESLint. If we head to our ESLint file, we can add a rule here for view max attributes per line. And we can actually tell it when it should wrap
based on the number of attributes specified in an element. And this is autofixable. So it'll automatically format it and put it on a new line if there's multiple attributes. And we will say this should result in an error. And then we can add some options. So I'm going to add the single line option and set the max number of attributes to three. So if a line has more than three attributes, automatically wrap it to have each attribute on its own line. And then if there are multiple attributes each on a new line, we'll set that to a max of one. So if we've already done some manual formatting like did a return and we have a single attribute on that line it'll automatically just wrap all of them. So with this llinter rule now if we head back you'll see that we're getting a llinter error. But if I do save it automatically fixes. So I like having this llinter rule here because this really gets out of hand if you have a lot of attributes. I'm actually going to go ahead and run a lint fix on the whole codebase because I know I have a lot of other places in the codebase
where there are multiple attributes on a line. We probably should have done this on another ticket because if we were working on a team and I format this, we're actually going to have a bunch of changed files. I'm okay with this for now. We'll just do a pnpm lint fix. Actually, if we do a pnpm lint first, we'll see how many files it's going to touch. Yeah. So, dashboard is going to get updated. The ad page is going to get updated. And the off button is going to get updated. So, like I said, this probably should be on a separate like formatting commit, but we're just going to include it as part of this commit.
So, we'll do a lint fix that should be able to autofix those to put the attributes on a new line, and we can keep moving. So, what we were in the process of doing is setting up this conditional class binding. So instead of hard- coding the input class here, we can say that only apply the input class if the type is equal to text and then only apply the text area class if the type is equal to text area. So now we have a nice and reusable component. We can pass in all of these props and it's automatically going to render all this stuff out for us. Let's use this component now. And we called it app form field. So if we head back to our form now, instead of all this, we can create an app form field. We can set the name to name. We can set the label to capital in name. We can set the type to text.
And now that I'm thinking about it, we should set text as the default. So that way they don't have to pass it in if it is just a text type. So we'll make this optional. And then if it was undefined, we'll default to text. So use the type value or just default to text. And then we'll do the same thing here. So apply the input class if type was not defined.
So we'll just say not type or the type is equal to text. So this is nice because now we don't have to specify text every time we want to use it. So over here we don't have to specify type text because it'll default to text and then we can pass in the error which is going to be errors.name and we'll bind that value there. That looks good to me. So let's just test this out with the first one. Let's just remove name. Now we have this nice reusable component right there. If this works, we will replace all of the others with this reusable component as well. Okay, so it still shows up on the page. That's good.
Does it validate? It does. Does it validate on blur? It does. And then will it submit? Sweet. So, I'm going to go through and replace all of the others with this reusable component. And just like that, our form is nice and clean, and we'll be able to reuse this app form field component in the other parts of our app where we're building out forms as well. Now, one issue I'm noticing is we're giving this description a class of text area, but because we're using that field component from validate, it's still behaving like an input, right? You can see that it's just all in a single line, it actually like doesn't wrap. So, one thing we can do is when we are rendering it out as a text area, we can use the as attribute here. So as is a built-in attribute inside of Vue where you can change the type of element that this will render as. And in this case we just want to use the type here. So we'll we'll bind it. And if the type does not
exist, then we'll default it to input. And so now if the type is text area, this will actually render it out as a text area and allow like multi-line. Otherwise, it'll render it out as an input. And so now you can see it's it's nice and wrapping. So this behaves as we would expect the text area to behave. So that's looking good. Let's head back to our issue and check some boxes. So we are validating the coordinates. We are validating the fields before submitting.
show confirmation if unsaved changes in form
Now let's handle confirmation dialogue shows when leaving with unsaved changes. So if I were to put some values in here and let's say I worked really really hard on this description. If I go away to another page, it instantly loses that state and then when I head back to this page, it's empty. I don't know about you, but I hate when this happens on websites. So, what I want is if a user attempts to navigate away, we'll say, "Hey, are you sure you want to do that?
You're going to lose any unsaved changes." And then if not, they can continue editing. We'll do the same thing when they click this cancel button. We'll be like, "Are you sure you want to do that?" And to do this, we're going to use on before route leave. So this is something we can tap into inside of a component and we can do something before they're leaving the specific page. So if we head to the dashboard page, we're going to add this here. And we really only want to confirm if they want to leave if they've actually changed the form itself. And so use form also provides this meta object here. And meta lets us know whether or not they've actually touched the form. So you can use meta.value.
So dirty means they've at least typed into one of the inputs because if they haven't typed anything, we don't want to say, "Hey, are you sure you want to navigate away?" We'll just navigate away. But if the form is dirty, we'll ask if they want to navigate away. And then here we'll say confirm is window.confirm. And then we can pass in a message. So here I will say, "Are you sure you want to leave? All unsaved changes will be lost." And you can see I'm getting a llinter error. So this is similar to like an alert in JavaScript, but we do want to do this. And I mainly just want to use the browser itself. We could implement like a custom dialogue that pops up and then prevents navigating away, but I think it's completely fine just to use the web browser because this will work across any web browser. So I'll say if they did not confirm, then we're going to return false, which means we will not let the next navigation happen. But if the form wasn't dirty, we'll just return true and we'll let the navigation happen. So
let's try this out. If I type in something here and then navigate away. We see the confirmation. Are you sure you want to leave? We'll say cancel. And let's just refresh the page. So it's completely empty now because the form isn't dirty. I can navigate away. And it doesn't prompt me. So that's great. And now let's just hook up this cancel button because clicking the cancel button should behave the same way as clicking away to another page. So to do this, we actually want to go back. We can use the use router hook that's built into NX use router and then router has a method on it called back. If you look in the Nux docs, they have a lot of other methods like back forward go. We're just going to say back. And so wherever they were before this, it'll take them back there. So when this cancel button is clicked, we want to say router.back. And that will take them backwards. So if we look at the full flow, I'm a user. I head here. I want to add a location. I try to cancel. Are you sure you want to do this? No. Are you
sure you want to do this? Yes. That then takes me back to the page that I was on before. So, that's looking good. We also have our icons on our buttons. Now, we can work on actually showing the loading spinner and putting it into the database. Now, for this, we're going to create an API endpoint. So, if we head to the server folder and then the API folder, this is where we're going to create our API routes. If you remember earlier when we set up better off, that itself is a route handler, but better off is handling everything else. Now, we're going to create our own custom route handlers. So, inside of here, you could create a locations folder and then put all of the route handlers inside of there. If you check out the next docs, each of these files can have a method name on them and then it will respond to that specific method. So, we could have like API/loations/index.git git and that would respond to any git request on API/loations. I'm actually going to name the files locations.get, locations.post, etc. Uh because it can get pretty out of hand if we have a bunch of index files.
create location API route
So, we'll do that. Inside of here, I'm going to create a new file called locations.post. So, when we receive a post request on API/loations, we're going to attempt to put that location into the database. From here, we need to define our event handler. And now we should get access to the body. If you check out the NXT docs here under server and API to get access to the body, they have this built-in method called read body and that will give you the body. But we do want to validate this body using zod. So there is this read validated body that's built into H3. So we can use the same schema that we used to validate on the front end. We can use that here and pass it into read validated body. So here we get access to the event. Then we can say the result is awaiting read validated body.
validate location before insert
Pass in the event and then we can pass in our validator. In this case it's insert locations safe parse. So safe parse will not throw an exception. We'll get access to the error if there was one. And so we need to make this an async method so we can use a wait. And then if we take a look at result, it has two things. So if results success is false then that means result.error has some validation error on it. But if results success is true then result.data will be the actual validated data that we want to put into the database. So let's handle this. If result.success was not true we can send back an error. So built into NX is this send error method and we can pass in the event. And then they also have this create error method where we can pass in all of our options. So in this case we want to set the status code to 422 which is unprocessable entity meaning you sent bad data to the server. And then we can
also set the status message. And so this will be the error that we display to the user. For now I'll just say invalid body. We'll make it nice and include all of the errors if this works. And then if there wasn't an error for now we're just going to return result.data. Now, this is the spot where we would actually insert it into the database, but I just want to make sure everything is nice and working here first. So, let's head back over to the dashboard. Now, inside of handle submit, we can try to call this endpoint. So, built into next is this thing called dollar sign fetch. And this is built on top of a library called oetch. And one of the nice things about it, it is completely type safe. So, you can see here that it is suggesting all of our API endpoints. So, that's great.
display server errors on form
So, we can call these. And then on top of that the return value is also type safe. So I'll show you that in a second. So here we'll specify the method as post. And then another nice thing about oetch is you don't have to stringify a body if it's JSON. You can just pass in that body directly. And this is going to get stringified behind the scenes for us. Now I'll need to make this an async method. We should get back the inserted data if it was successful. And then I'll await that. And now you can see if I hover over this the type actually flows through. So it knows that if this was a successful response, it's going to respond with that inserted data. But the other cool thing about oetch is if the server responds with a non-successful status code, in this case, if it responds with a 422, this will actually throw an exception. So in that case, we want to try catch it. So if it was successful, it got inserted, we can do what we want after that. But if it wasn't successful, we want to get access to that error message. So right here, I'm going to grab the error. And this is
E as the error type. And for now, we'll just log out the error. And if it was successful, we'll log out that inserted value like so. So, let's give it a try. I'll do a quick refresh and we'll add all of our fields. I don't actually know the latitude longitude. We're just going to put some values in for now. And then I'll open up the network tab and see what happens. So, let's add it. We see it makes a post request that responds with a 200. We can see that it sent the data from the form and then it responded exactly with the data that we sent it.
So, it's nice and hooked up and validating it on the back end. But to really test out that validation, let's make it so that we're not even validating on the front end. Let's comment out our validation schema here and make sure the server actually responds with a validation error. So, let's just completely refresh the page, clear everything out, and now we'll try submitting a completely empty form. The server responds with the 42:2. And if we take a look, we can see it's got that status code and then that status message there. And if we look in the console, we can see that the type here of the error is fetch error. So let's actually use that type instead of error. So this should be a fetch error. It doesn't autoimp import from anywhere, but I know that this should come from oetch. So let's try importing it in like so. And now we should get some nice type completion. So what else do we have access to? So we have the cause and then we also have status message. So this is that status message that we set on the back end. Let's log that out and that will be what we display on the form if there was an error. So let's clear
everything out, try submitting, and then it gets invalid body. So I actually want to take that error message and display it on the form here. So we'll use an alert for this. If we head back to Daisy, check out their alerts, we want an error. It's going to look like this. And then we need a state variable to hold on to the submission error. So right here, I'll create a variable.
Let's call it submit error and we'll default it to the empty string. But then whenever an error happens, we're going to set submit error.value to be error.st status message. And then status message could be undefined. So we'll say if there wasn't a status message, we'll just say an unnown error occurred. And this might happen if there is some other issue. Like let's say there's not a validation error, but maybe there's an error inserting into the database or connecting to the database. We're not setting any custom status message in that case. And so that's when this would potentially get triggered. But now we want to display this on the page. So right above the form, we'll add that alert from Daisy UI. And then we only want to display it if the submit error has a value. And then we'll display that submit error right here. So now if we submit without validating, there we go. It says invalid body. Now instead of saying invalid
body, I want to actually list out those validation errors. So let's head back to the back end and we can change up how we're actually sending back the error here. So here under status message, I want to create a single message that describes all of the errors. And for that, we're going to iterate over result.issues. So those are all of the ZOD issues. So here I'll just say the status message is result.isssues. And then we're going to map over each one of those issues. And we can grab issue message and then also issue.path.
So issue.path is the actual field. So that'll be like name or description or latitude or longitude. So we'll say issue.path. Path is an array. So we want to turn that into a single string. And then we want to say like field name colon error message. So, let's actually put this into a template string. We'll add the field name there. Give it a colon. And then we'll display message.
And then we'll join each of those error messages together. Now, they're all going to be on the same line because of the way status message is handled on the front end. So, we're just going to separate them all with a semicolon space. So, it'll say error message colon other error message, etc. Let's format this and then include this status message in the response. So and then let's give it a try. So if I submit with invalid data now it says name required lat expected number received nan long expected number received nan. Awesome.
Now another thing is because we have those validation issues we could include them in the response and then actually show the validation errors on each of the fields here. Now in our API route here, we also can include some data and use this data on the front end. And in this case, I actually want to respond with an object where all of the keys are the specific path and then all of the values are the error messages because that's the format that validate expects for an errors object. So we'll reformat this in that way and then we can directly set those errors on our form.
So we're going to do some similar reformatting here, but instead we'll call this data. And instead of a map, we actually want to do a reduce. So we're reducing this whole thing into a single object. We'll call it errors. And the initial value is just a blank object that we're then going to attach all of those errors to. Now, TypeScript would complain if we tried putting new properties on this. So I'm just going to make this a generic object. We'll say this is a record of string string. So it'll be an object that has field error name, field error name. So inside of the reduce, we always want to return that errors object that we're building up.
But we want to set the error for each field. So we'll say errors at issue.path.join. So that'll be the field name. And that's going to be equal to issue message. So data is now going to be an object where all the keys are the fields and all the values are the error messages. and we'll respond with that right here. So if we head back to our dashboard, so right here, error.ata is now going to be that object. Let's go ahead and log that out here. And if we did that reduce, right, we should see that errors object in the console. So let's clear everything out, refresh, try submitting, and we can see we have all of that. Apparently, we need to do data.data, but let's just make sure data exists and then access the data property. So now if we submit this, yeah, that's what I want to see. So it's all of our errors, right? We have lat error, long error, name error. And so now I want to set these errors on the form itself. And there is something
built into validate that'll let us do that. So right here whenever we use the form, there is an option to set errors and we can pass in that errors object that we got back. So right here we can say set errors and then pass in error.data.data like so. And because it's in the correct format, it's going to display those errors on each of the form fields. So now if I submit, boom, it sets those errors on each of the fields as well. So the user has some nice feedback there. Now, just in case something else went wrong, like it wasn't a validation error, I do want to make sure that we only set the errors if this exists because there could be an issue with connecting to the database or inserting to the database. So let's simulate that. Let's say for for whatever reason this thing throws an error. Let's just throw a new error. Oh no. Our form should be able to handle that. So it should display oh no at the top but then not set any of the field errors. Yeah. So this is setting it as server error. If the error was an actual next error, then the status message
would be potentially a little bit more descriptive. But this is what we want to see because if something went wrong, we want to display that as well. Okay, it's looking good so far. If we look back at our issue, we do need to display a loading spinner while the creation is happening. So, if we head back to the form, we're going to need some loading state. So, right here, I'll create a new ref. Just call it loading. And we'll set this to false by default. Then, when we make the post request, we'll set this to true. And then after all of this is done, we'll set this to false. Now, each time I submit, I want to clear out the submit error because they might have had some validation errors or something went wrong and they're going to try to submit again. So we will clear this out back to the empty string if they submit again.
loading state during create location
Now let's tap into this and use it in the form. So if loading is true, I actually want to disable the inputs and the buttons and then also display a loading indicator. So for the button here, I'm going to set this is disabled if we are loading and we'll bind it. And I'm going to do the same thing for the button. And we actually want our forms to be disabled as well. So it it'll indicate to the user that something's happening. They can't really edit any data right now. So I think we'll update our app form field component to also take in a disabled attribute and then disable the underlying input if disabled is set to true. So we'll pass this down to all of the instances here and then we will use it in the form field component.
So, so if we head to components app form field. Now, we also want to take in a disabled prop. This will be optional, but otherwise will be a boolean. And then we need to pass disabled down to the field here. So, we'll bind disabled to the disabled prop. And so, to test this out, if we head back to the dashboard page, let's default loading to true. And now everything in the form should be disabled. And it is. I can't click in anything. I can't click any buttons. So this is the state we want to see when the form is submitting. But we also want to show a loading spinner here on the ad button. So let's grab a loading spinner from Daisy. Probably use the small one. And then if adding is happening, we're going to display that loading spinner. So if loading, show the loading spinner. Otherwise, show the ad icon. So now by default when submission is happening they see that little loading spinner and then the data will
come back. So it's no longer default to true. We'll set it to false. And now because I'm running in local dev it happens instantly. So you don't really see the loading spinner but this will definitely be useful whenever we're running in production. Um so this looks good. And then let's make sure that we can actually submit that data now. So let me fill out the form. And if we submit that clears the error and we got the data back from the API. So at this point we're ready to insert that data into the database. Now let's go ahead and uncomment this so that way we're actually validating the data on the front end before sending it to the back end. But the important piece is that we are validating it on the back end. Now if we made it here, it's time to insert into the database. So let's go ahead and import our DB connection. So we'll import it from lib DB and we'll say we want to insert into the location table.
insert location into db
So I need to import location from the schema and then we can specify the values that we want to insert. In this case, we're inserting result.data. But you'll notice we're getting a type error because the data that we validated does not have the user ID or the slug. It's up to us to create those. So what we'll do here is spread this into the object and then specify the user ID. We'll of course grab it from the user session and then also specify the slug. For now, I'm just going to do some It's very simple slugification. Once we get this all working, we'll actually install a library that does some slug creation for us. But for this, I'll just say result.data.name. Let's replace all of the spaces with dashes and then two lowercase the whole thing. So, very simple slugification. We'll use a library in a second once we know that this is working. And then we need the user's actual ID. So, if you remember
access logged in user in API route
earlier, we set up that off middleware. Let's take a look at it. It is grabbing the user's session and then redirecting if they're not logged in. But one of the things that we could do here is attach this session info to the event context. So that way in any other API route handler, we get access to the session if it exists. So let's do that. We'll grab the session and then here we can attach that session object to the context. So if you look in the nux docs, you can see here under extending the context, if we say event.context, we can put whatever we want on there and then access that in any other route handler. So right here I'll say event.context do user is equal to session do user and if that exists because it's possible that they're not logged in. But if they are logged in then this will have the user object and then we can put it onto the event context here. So now in any other route if we access event.context context user that will be the loggedin user. So let's do that inside of our locations endpoint
here. And essentially we don't want any of this to happen unless the user is actually logged in. So here we can say if event.context user does not exist, we want to throw an unauthorized error because users that are not logged in cannot create new locations. So if the user doesn't exist on the context here, then we're going to return an error, similar, but it's just going to say unauthorized. So we'll send the status code of 401. Status message will be unauthorized, and we won't send back any data. So now you must be logged in in order to create this location. Now down below, I actually want to get access to user. ID, but by default, user is just the any type. If we want some good type completion here, we can actually extend the H3 event context type. So in my lib folder, I'm going to create a new file.
We'll just call it types.ts. And we need to override the H3 event context type inside of the H3 module. So we'll say declare module H3. And then in here we'll say the H3 event context. And we can specify all of our custom properties. So we'll say that this has a user property that is optional. And this is of type user. So we can actually import user from better off. But one of the issues about the default user type is the ID is string.
If you remember when we were setting up the schema, we actually turned these into integers. So here's what I'm going to do. I'm going to use the TypeScript utility called omit to grab this type and then omit the ID property. So now we get a user that doesn't have an ID property. And then I'm going to compose that together with a type where the ID property is a number. So this looks good. The context will now have a user object. Now one issue is when I save this, it turns it into a type and I actually don't want that. And this is actually coming from my ESLint config.
So I'm going to disable that rule. I'm going to say disable consistent type definitions because in order to override the underlying type, it does need to be an interface. Now, with this type definition here, if we head back over to our API function, when I hover over the context, you'll see that user now has the correct type there. So, down here, I should be able to say event.context do user id. There we go. And so, now we're inserting a location with all of the validated data. We're creating a slug.
We're passing in that user's ID because they own this location. And that should be good to go. So I'll grab the created location. We need to await this. And then we also need to say returning. So that will return the inserted data. But returning actually returns an array. So we just want to grab that first inserted one. So we'll use dstructuring there.
insert location into db with userId
And now we'll return the actual created data. So our insertion endpoint is ready to go. Make sure the user is logged in. Validate the body. If it's validated, insert it and return it. So now back on the front end, we are currently logging out that inserted value. So now we should see a location with an ID, with a user ID, with the created at, updated at, all of those fields. So let's give it a try. Let's clear the console. We'll do a hard refresh. Moment of truth.
We're going to add Denver, the coolest place on Earth. Now I actually get am going to add the real latitude longitude. So, let me go grab that really quick. That looks like this. And here we go. Let's hope for the best. And look at that. It inserted it into the database. So, it has the created at field. It's got an ID. It has the user ID. It has an updated at field. It's got a slug. It's looking good. So, at this point, after a location is inserted, we likely just want to redirect back to the locations page, which in this case will just be displaying all of the locations.
redirect after creating new location
and this latest location will pop up there. So let's handle that here. So right after creation I'm going to use navigate to and then just say we want to go to slash dashboard. And for now we're not using that returned value. So let's try creating a new location. Let's also add uh New York City, the Big Apple. So now we'll add it and then it should redirect us back to the locations page.
Now, it's possible that the before route navigate is going to kick in. We might need to store the fact that we did just create a thing and we actually do want to navigate away. Let's see. Let's add it. Yeah. So, it it's always prompting us to do this. So, in that on before route navigate, we need to check to see was this form actually submitted? And if it was, we do want to allow them to navigate away. So, over here, we're checking if the form is dirty, but let's also check to see if the form was successfully submitted. So, I'm actually just going to create a new variable for that. We'll just call this submitted.
And if the submission was successful, we'll set submitted to true. And then in on before route navigate, if we have not submitted and the form is dirty, then do the confirmation. But if we have submitted, then it's just going to let the navigation happen. So at this point, we should already have two locations in the database. Let's add one more. We're going to add San Francisco. So this looks good. Let's add it. Moment of truth. we get redirected back to the dashboard because I've inserted multiple things into the database. Let's actually spin up Drizzle Studio and look at that data in the database. So if we do a PNPM Drizzle hit studio, we should see those three locations in the database. Yeah.
So there are three. We've got Denver, New York City, and San Francisco. You can see that we have our simplified sluggification here. All of the data looks good. Awesome. Now, there's one more thing we need to take into account for this ad location page. Check this out. I am a hacker. I have built out this little web page that has a form on it. And it's a super basic form. It has name, description, latitude, longitude.
csrf protection
But you'll see that the action is pointed to my next app. And the method here is post. Now, to be clear, this is a completely separate website. This might as well be superbhacker.com. It's a separate website and our site lives on local host 3000. But check this out. What happens if I send some data?
Is it going to work? Click create. Well, wouldn't you know it, we were able to submit data from a completely separate website. Uh, and it worked, right? We got we got back uh a successful server response. And this is a pretty trivial example here. One thing you could do is make all of these form inputs hidden, right? You could just have a website with a banner that says you just want a a free iPhone and then when they click it behind the scenes it could be submitting a form that changes your details on some other website. Now to see why this is happening let's look at the network request. So we click create.
It works but the main reason this happens is because we're using cookies for authentication. And when we're using a regular HTML form it automatically includes all of the cookies in the browser in the request. So if we look at this request here, we can see that it included our better off session token. Even though we were on a completely separate origin because the request in the form was going to localhost 3000, that cookie was set in our browser for localhost 3000 and it included that cookie. So that's why this was able to work. Now we need to protect against this and this is known as cross-sight request forgery and it happens if your website accepts form data. So if we look at this post request that happened, you can see that the actual request is form data, right? It's not sending it over as JSON. The code that we wrote is using JavaScript, sending it as JSON, but this is happening via the web browser and being sent as form data. And by default, when we use that read validated body function, it will read in any kind of uh body. It reads in form data. It reads in
JSON. So in order to protect from cross-sight request forgery or CSURF, we use what are known as CSURF tokens. And there's actually a module for this called nux csurf. And essentially what it does for every single form that needs to use curf. It creates a unique token for each page load. And that token can only be retrieved when that page is actually rendered. And then when you send the post request, you send that token along with it. And then you validate that token on the server side.
So we'll install this module. And then anytime we're making posts or put requests, we'll use this dollar sign cesurf fetch instead to make sure that it attaches that token. And once we've done that, this attack will no longer be possible because this attacker's page here will not be able to get that Curf token value. So let's fix this. We're going to install this NXT Curf module.
So we'll do PNPM DLX nuxy add. And now we have to use the special fetch function. So I'm going to leave all of the default options. These are the options that get set by default by adding the module. And if we take a look in our Nux config, it's now added that module. So now that we have this module, let's just try adding a location from within our app. Click add. Oh no, a Curve token mismatch. So automatically by adding that module, any post request, put request, you can see the defaults here, or patch request, all of these validate the token. And if the token isn't in the request, it's not going to allow that action to happen. So in order to automatically include the token, we can use dollar sign cesurf fetch. So if we head to our ad page right about here, instead of just dollar sign fetch, we'll use dollar sign cesurf fetch. And we will need to import this in. So use nuxap gra dollar sign csurf fetch. And now it'll automatically include that csurf token in the request. So let's
give this a try. We'll add it. The post request was successful. And you can see that it got created. And if we look at the request, it actually included it in a header. So if we look at our request headers, it included this CSUF token header and then that token was validated on the server side. But now that we're protected, our hacker site shouldn't be able to forge requests like that. If they try to send a post request there, look at that. We get a Curve token not found. Now, it's important to note for just like regular fetch requests from some other origin, those are still restricted to cores or cross origin resource sharing. So, even on this this hacker man website, this couldn't write fetch code that tries to request all of my locations because the browser will not include the cookies in that fetch request because we're on a completely separate origin. We really only need to protect the methods that are supported by HTML forms, which are just post and get. So, this module automatically protects for those those post requests.
Later on, we'll have like patch requests and delete requests. will still use this curf module, but the browser doesn't have a way to submit a form that is a a patch request or a delete request. So, we are protected from those by default. And because logging in with social is a post request to our backend to get that redirect URL, we do need to include the CSUF token there. So, you can see I just create a headers object, append the CSRF token, and then add it to our fetch options for OPC client signin social.
Now, we also need to do this in our sign out method because that does make a post request to sign out. So we'll do the same thing. We'll get the current CS surf token and then this sign out method also accepts fetch options. So right here we'll pass in those fetch options. So we're done. The loading spinner displays. We get redirected back. Let me commit it, push it, pull request it, deploy it, and then we'll move on to the next story. All right. Next up, we have location slugs are URL friendly and validated to be unique. So this says server unique constraint error message is returned by the API. All special characters are removed and replaced in the slug. And if an existing slug exists in the database, append a short generated code. So right now, if we take a look in our database, we have three locations, Denver, New York City, and San Francisco. And this slug was generated based on the name. So if I try to add another location where the slug will be generated in exactly the same way, we should get a server error because we set up that unique constraint on the slug in the database. So let's
validate unique location slug and name
just give this a test really quick. So this will attempt to create a location called Denver. But if you remember in our backend code, it's going to generate a slug that's just a lowercase version of the name. And so if I add this, we do get a server error, but it would be nice to display a more useful error that says something like slug already in use or name must be unique. So let's head to the codes. I'm going to get back to the main branch and then we'll check out a branch. In this case, it's issue number 61. For you, it will probably be a lower issue number. So, TL-61 and then let's head into the code that tries to create the location. So, here we're in locations post and this unique constraint error is happening when we attempt to insert it into the database here. So, first let's go ahead and make sure we handle this error. We're just going to wrap this in a try catch and if it was created, we'll return it.
Otherwise, let's actually just log the error right now and then we'll throw that error. So, let's try inserting this again. Click add and then let's take a look at the server logs. Now if that error occurs, we can see it logged here. So SQLite constraint SQLite error unique constraint field location.slug. So this is saying that the slug needs to be unique. You can see that it is of type response error here. And drizzle actually has a built-in error type that we can use so that it's correctly typed.
So right now error is of the any type, but we know that if this throws an exception, then it should actually be a drizzle error. So here's what we'll do. We'll just grab this as E and then we'll create an error variable that is a Drizzle error and we can import that in from Drizzle OM like so. And now that we know the error type, let's log error message. And this is what we'll potentially use if we craft a custom response. We can use that message to then set the status message as something like slug must be unique. So here I'm just going to label this as insert error. So we can see it in the console.
And let's try again. So if I try inserting this, we get a server error. And then over here we should see insert error SQLite constraint. So now I'll just match against this error message here. I'll say if error dossage is equal to SQLite constraint SQL error unique constraint field location slug then I'm going to throw a custom error like this.
And the status message in this case we can just set it to be custom. And we'll say slug must be unique. And then we'll let them know the name is used to generate the location name is used to generate a slug. Do it like this. We don't have any data. And then in this case, we can use the status code 409, which is a conflict because there's a conflict when trying to insert this.
Now, if it wasn't a SQLite constraint error, it could be like a database connection error or something else. So then we'll throw the error here. But now that we're customizing the error message, this should come through on the front end because we're tapping into when an error happens. So now if we try to create it, look at that. We get a useful error. Slug must be unique. The location name is used to generate the slug. Nice. But now let's actually do some slug generation because our code here literally just lowercases it and then replaces all spaces with dashes.
generating slug during location insert
But if they include special characters or other things like that, this isn't going to handle that. And we can also before we insert, make sure that that slug doesn't exist. and then if it does put a little short code on the end and so that will allow two different locations to have the same name but they'll have a unique slug. So first up there is a package on npm called slug and this is what we'll use. It's a pretty small package and literally you just pass some text into it and it knows about special unicode characters and special characters and it'll replace all of those with dashes by default. So let's add this and then we'll install the types. So that looks good and then now instead of doing it manually we'll just bring in the slug library. So right here, we'll just say slug of result.data.name. And then we can import slug from that library we just installed. And so now this will automatically slugify it for us. Now the next thing we'll do is make sure that slug does not exist. And if it does, we'll just append a short code on the end that's like randomly generated. So before even trying to insert, we'll create the slug. And we're going to have
a collision between a variable named slug and the library slug. So I'm actually going to rename this as slugify like this. And that way it won't collide if we have a variable named slug. So now I can extract this off into a variable called slug like this. And then we want to check to see does it exist in the database. So to figure that out we'll just query it. So I'll do db.query and we'll use the OM style querying because we're just doing a select here. And this allows me to just choose the table. And then I want to find everyone where and here we want to check against that slug column. So we can use eq which comes from drizzle. We'll say where location.
slug is equal to that slug that we're trying to find there. And because slug needs to be unique, we'll actually just do find first. So that way just find one that already has this slug. And then if we found it, that means we need to generate a random ID and put it on the end. So for this, there's another library I like to use. It's called Nano ID. And this generates URL friendly random IDs. So I'm going to go ahead and install this, but it is customizable.
So, I think what I'll do is generate like a five character short code and then put that onto the end of the slug if there's one that already has this name. So, let's go ahead and install Nano ID like so. And then if we check out their docs, they have a few different ways to use it. And so, in this case, I just want to use custom alphabet because I want to allow numbers and letters, but I want it to all be lowercase. I don't want there to be any confusion about uppercase versus lowercase. So, I am going to use the custom alphabet function. And we'll generate them of length five. And I'll make sure to include the whole alphabet.
So we'll bring this in here. And then when we create the nano ID, we'll do that here. We want this to be of length five. And I want it to include all the letters and numbers. So I'm going to type out the alphabet like so. And so this should give me a five character random code. I'm just going to append it on the end of the slug here. Now technically they do have another library. It's called NanoID dictionary.
and they have a bunch of dictionaries that might be useful to you like hexadimal lowerase uppercase alpha numeric. I only want lowercase alpha numeric. So I didn't want to install an extra library just for that. So this looks good to me. So now if it was existing we need to append this nano ID on the end. So then we'll make slug mutable. And in this case we'll just append it to the end. So I'll say slug plus equals and then we'll just have a dash and then throw in that ID like so.
And so this should prevent a collision, but it's possible that the randomly generated ID does actually conflict with the database. So after I've generated this ID, I also need to make sure that this generated ID does not exist in the database. And so the way I'll do this is just re-query the database if I generated an ID that already exists inside of there. So let's say existing just starts off as a boolean. So we'll do the query and then if it was truthy, then existing will be true. If it was falsy, then existing will be false. And then instead of an if statement, we'll use a while statement. So while existing is true, then keep on keeping on. And so in this case, we'll create the new slug and then override it. And to prevent conflicting here, I'm actually going to rename slug to original slug. And then we'll create our let's call it ID slug.
And that's just going to be the original slug with the nano ID on the end. And then we'll query the database. So we'll say existing is equal to that exact same query. And in this case, we'll pass in our ID slug. And actually, I didn't need to rename this to original slug. We're going to call it slug because we have this ID slug variable here. So, the way this will work is query the database to see does that slug exist in there. If it doesn't, we'll just insert that location. We're good to go. If it does exist, we're going to append a random ID onto the end of it and then make sure that that random ID does not exist in the database. If it does, we'll do it again. There are potentially better ways to do this. Like, we could first query for every slug that starts with this and then we have the list and we don't have to keep querying the database. our database is small enough. I'm not worried that this will turn it into an infinite loop. But if you have a larger application, you would worry about that because for every user trying to create a new location, you potentially will query the database multiple times. But like I said, I'm not optimizing it right now. This is completely fine for the the simple app that we're building. And then after all that, if we found one that was
not existing, then we can override slug to be the ID slug. And then we'll make it down here and we'll be inserting with that slug that has the ID on the end. So this should be good from now. As some homework for you, I would say try to optimize this. Like I said, you could instead of doing a find first, you could do a find all with a like query and then you have the full list of slugs that are similar. The one issue with that is you're going to get all the slugs that start with this location name, but there could be two locations that start with the same name, but maybe another one has multiple names, and then that's not actually included in your collisions.
So, that's why I didn't want to go down that path. This is easy enough for now. And so, I'm realizing now that this custom alphabet returns a function. this would put the whole function in there. What we actually want to do is just extract this out here so it's reusable and then we'll have ourselves an ID variable here. So right here I can say the ID is nano ID invoked. That will give us a random one and then we can pass it in there. So now with all of this, if I attempt to insert a location that has the same name as some other location, this should append a random ID on the end of the slug. So let's give it a try. We'll add it. We didn't get an error. And if we check Gizzle Studio, do a refresh here. Now we have another location that has a unique slug with that ID on the end there. So this is looking great. And this logic essentially works for two different users that try to create a location with the same name because we do want to allow that, right? Two different users should be able to have a location called Denver. But another constraint we could add is a single user shouldn't be able to create a location with the same name
because it probably wouldn't make sense for the same user to have two different locations called Denver. Um they should make it unique enough. This could be like Denver vegan restaurants or Denver parks and that will make sure that they're unique. So let's add one more constraint and we can actually do this at the database level with a composite key and we can say that the combination of the name of the location and the user ID should be unique. So one user cannot have two locations with the same name Denver. But you can have two different users that have the same location name called Denver. And if you check out the drizzle docs under the unique constraint, you can actually have a unique composite key. So you can pass in two column names and the database will make sure that the combination of those two column names is unique together. So let's actually do this on our schema on the location table. So if we head to lib db schema location, we'll then add this callback function here that returns an array of constraints and we will create a unique constraint. This will come from
unique location name per user database constraint
SQLite core. And then we can say on and pass in the two column names. So I want this to be unique on table.name and table do user ID. So one user can't create two locations with the same name. So with this I'll go ahead and generate the migration and then migrate the database. And then we'll try to insert a location with the same name as one that already exists. So we'll do a pnpm drizzle kit generate. And then we'll do a pnpm drizzle kit migrate. And then when we attempt to migrate, it's already failing because the data in our database doesn't match that constraint, right?
Because these two rows are from the same user with ID2. So I'm just going to go ahead and delete this one. And then I should be able to migrate. But now when a user attempts to insert a location with the same name, we should actually get an error. So let's go to add Denver again. So now this should attempt to generate a unique slug, but it will actually fail on the insert because the name is the same as one that already exists in the database. So, let's give it a try. And we're getting a not found error. But I looked into the database here. And you can see that in the account table for better off, the user ID is a text column. And because we updated all of the off columns to be ins, this is storing it with a decimal.
And then it's not finding the user. So, we actually have to go way back and head back to our off schema. And then anywhere there's a user ID, we need to make sure that this is an integer column. And so there's just two spots, the session table and the account table. But we do need to make sure that this is an integer like this. And now because I had to change these column types, we really should start from scratch. Now, I said our schema was in a spot where we wouldn't have to create more migrations, but as we're building, I'm realizing this, but since we're in development, I think it's completely fine to just wipe these out and create our base migrations now that we have our updated schema here with our updated constraints. So, I'm actually going to delete this migrations folder entirely. And really, you should only do this if you're not fully in production yet, right? We're we're still in development. There's no production data that's going to get lost here. So, I'm actually wiping out that those migrations, and I'm going to delete all of these local database files. So, I'm going to kill the database here, delete
oops - reset entire db / migrations
all of these, and we're starting from scratch. So, I'm going to generate a single migration that has all of the schema here as it currently exists. Now, one thing you could do is pnpm drizzle kit push. This is one way to work in development instead of creating these migrations. This just directly pushes the schema to the database. But I like to have the migrations in my code so we can get an idea of what changed over time once we're in a stable state. And at this point, I think we're in a stable state. Uh you may see by the end of the tutorial, maybe we do this one more time, but I think we are. So, I'm going to go ahead and generate the migrations.
So, now we should have a single migration that does all the stuff right. It creates all the tables with the correct types. So user ID is of type integer. And it also created the unique constraint on the location table. So that way name and user ID must be unique. Uh and then from here we'll start our database back up in the app.
And then we should be able to migrate the database. So we'll do a pnpm drizzle kit migrate. That will create all the tables. But now we're completely starting from scratch. If we reload Drizzle Studio here, now our tables have nothing in them. So, we're we're completely starting from scratch. You can see we got logged out cuz that user doesn't exist anymore. But I think our our schema is in a much better state.
So, now if we go to add a location like Denver and add this that gets put into the database, we should see over here that we have a user with a session and then they have a location. But now, moment of truth, let's try inserting another location with the same name. We add it. That's what we want to see. Okay, so if we look back at the logs now, we see this unique constraint error where a user tried to insert a location with the same name that already exists for that given user. So now before we even try to generate a slug or try to insert, we should actually first make sure that this user hasn't created a location with this name yet. And we'll just do that with a simple query. So, if we head back over to our API, before doing all this Slugify stuff, we want to do a find first where name and ID is equal to what they're trying to insert.
show unique location name error
So, we'll say existing location is db.query location. We're going to find the first location where the location.name is equal to result.data.name and where the user ID is equal to this user ID. So for that we can pull in the and from drizzle OM pass equal into that and then we just want a second equal statement. So the second equal is going to be location user ID is the user's user ID which is event.context user ID. And so after validating before even trying to insert anything or create the slug first check to see did this user already create a location with this name. If we did we can immediately return an error. So here we'll say if existing location exists then we can send back an error. In this case it's going to be a 409 conflicting status code. In this case the status message will be a location with that name already exists. Awesome. So now if
we head back to our app and we try creating this we get a much more readable error that says a location with that name already exists. But if I make it more unique like Denver parks and then try to add this that actually does get created. If we head back to Drizzle Studio and refresh, now we have both those locations in the database. So, this was a bit roundabout because we handled the unique slug case first. I don't really have a way to test with two different users right now. So, I wanted to handle that. But, we also needed to handle the unique name scenario. So, that should be good to go. And I added one more checkbox for us. Users cannot create two locations with the same name.
Now, because we updated the database in this way, in order to deploy this to production, I will need to completely overwrite our Terso database. So for that, I'll just delete the existing one. That will give me a new URL with a new token. Run the migrations against it like we did earlier. And then we should be good to go to work with all of this data in production. All right. Next up, before we move on to more features, we have some code cleanup to do. So I have this story here. Consolidate DB queries into a single module. So queries are moved to a single location so they can be reused throughout the application.
consolidate location table db queries
Now the way we've written the code right now is we have all these DB queries in this single handler, right? We read the database to find an existing location. We read the database to find an existing slug. We then have a dbquery that inserts a location into the database. So what we should do is pull these out to a single spot. So that way if there are API methods in the future that want to use these same methods, we're not replicating that DB query logic. So let's get back to the main branch. We'll create another branch for number 63. And now this will exist in lib DB. And then I'm going to create a folder called queries. And then inside of here, I'm going to create a file called location.
And this will have all of the queries for the location table. So if we head back to this API function locations.post, this first database query is finding an existing location. So we can refactor this manually, but there are some things built into VS Code that allow us to do this pretty easily. So if you rightclick the code you want to refactor, go to refactor. Here I'll just say extract to function in the module scope. And so we'll call this uh find location by name. And so that actually created this function down here that in this case needs to get access to the location that we're trying to insert and then the user. So let's just refactor this so that this gets access to let's call this the um existing and then this will be of type insert location. But in order to get that type we do need to infer it from our zod schema. So if we head to our DB schema and then location, I want a type that represents the data that can be inserted
here. So I'm going to export this type called insert location. And then we'll do Z which comes from zod.infer. And then we can pass in the type of insert location. And so now I have a TypeScript type that represents the data that can be inserted. So now that the type exists, this import here is the validator and the type. So we can use that there. And then we'll use that variable here. So instead of saying resultdata, we'll pass in existing. And then here we actually just want access to the user ID. So I'm going to pass in user ID, which is a number, and then pass that value in directly here. Okay.
So I have this reusable function. First, let's make sure we're calling it in the right way. So here we need to pass in result.data. And then here we need to pass in event.context user. ID. So we have this useful function where you can pass in a location that has a name and pass in the user ID. and it's going to check to see if it exists. Um, we can get rid of a wait because that's automatically going to be awaited. But now I want this function to exist in that queries file. So another refactoring we can do is we can select this function, say refactor, refactor to a file, and we're going to pull it over to our queries location file. Now, that failed, so I'm just going to do it manually, but it might work automatically for you. So I'm just going to pull out this function, put it in here, and then make sure we export it.
And then we're going to have to bring in all of those types. So we'll bring in the insert location. We'll bring in bring in DB. Bring in and and equal from Drizzle OM. And then we'll bring in our location table like so. Okay. So now we've pulled it to a separate file. Let's import it and use it. So now it should be able to find this. Yeah. So import that from our queries. So that looks good. Now we'll slowly get rid of some imports inside of here. And let's extract our next function. So So this is going to be a query that's find location by slug. So I'm going to extract this out into a function in the module scope.
We'll say find location by slug. And in this case, it is returning it as a boolean. I think what I'll do is just return the location by slug. And then we'll turn it into a boolean on the other side because I could imagine there are other parts of my code that will want to find a location by slug. So this is going to be nice and reusable. But then over here we'll turn it into a boolean after finding it. So here we'll do that. And now we can do a similar thing down here, but instead we'll pass in the ID slug. Okay, so that's nice and reusable. And then let's extract this function over to our queries file. We'll pull that out here in queries. We're going to export this. And then back over here, we can import it in. Now, this piece right here technically could be extracted into that queries file as well. And I think we'll do that especially because that's the spot where we could update it to use the more performant logic like I was talking about earlier. So I think what I'll do is I'll extract this all of these pieces right here into its own function that
says get unique slug. And I'm just going to do this manually. So we'll extract all of this. Then here I can say slug is find unique slug with the slugified version. And we will need to await this. And then I'll create that find unique slug function in my queries file. So here we'll have a function find unique slug takes in the existing slug and then creates that ID. So once we've done all of this instead of reassigning it here we can just return the ID slug like that. And now I'll bring in all that nano ID stuff that is in the API file.
So over here first import that function but then we can pull out nano ID and custom alphabet into our queries file. So put those there. This should behave as before. And then one last thing is we don't need find location by slug in this file anymore. Now the last query is the actual insert query. So this here will insert a location and return it. So let's extract this into another function. We'll call this insert location. This gets the insertable and this will be of type insert location and then our codes will do this and then return the created location and then it's also going to need access to the slug because the insert location doesn't include the slug and doesn't include the user ID. So we'll pass those in separately. So we'll grab the slug which is a string and then the user ID which is a number and then we'll pass all of those in. So this gets the user ID, spreads the insertable, and then finally
we'll return the created location. So that's looking good. Let's use this on the other side. So now instead of all this, we're going to say just return insert location and then we'll pass in result.data, the slug, and the user ID.
Awesome. So at this point, we've extracted all of those queries to that separate file. And if we need them when we're working on another API route, we can use them. I'll go ahead and remove these unused imports now as well. Now, there are other spots in here that are definitely going to be refactored because they're going to be used at other spots, like checking to make sure a user is logged in and creating a a readable ZOD error message. We'll refactor those when we get to it. Uh, but this should be good for now. So, right now, let's just test out the app.
Make sure all of the the pages work as expected because we haven't changed any functionality, but all the existing functionality should work. So right now I do have a location called Denver in here. So this should fail location with that name already exists. And if we look in Drizzle Studio, I think I I have two Denver and Denver parks. So let's actually just add San Francisco again.
We'll give it that latitude longitude. We get a server error. That's good that we're checking. Let's check the logs. So this is throwing unable to create unique slug. Maybe our logic was wrong there. So let's head to our queries. Ah, so I see we did have an error here. So, it's good that we're checking this. So, if it was not existing, then the slug that we're asking for was unique. So, we actually do just need to return that slug. You probably caught that when you were watching this, but I didn't. So, I'm going to update that. That'll actually use the slug that they tried because it is unique. So, let's try adding San Fran again. Right, here we go. All right, it inserted. We'll check Drizzle Studio. There it is. All right, so things are looking good. The queries got moved, so now they can be reused later on if we need to do similar stuff.
Let's commit this. Push it up. Merge. Move on to the next thing. Now we're merged and fully deployed. But I noticed that in production if I try to get like the name already exists error, it actually doesn't come through. So if we do this, it just says an unknown error occurred. And I found the issue is in production the status message is not said on the error variable. So if we look at our code here, so this is the code that submits the location to be created. And when we're running where nodev is equal to development, status message does have a value. But in production, status message is just the generic server message so that nothing is leaked. But what we could do is say error.data and if that exists, grab the status message otherwise grab error.st status message. And so if we check this when running locally now, if I do this and try to add it, the name still comes through. So, I'm going to push this change up to production as well. And we should see that more descriptive error
show form errors in production
message come through. And so, with that change deployed in production, now we should see the error message actually comes through. And this is good because we want to see those more descriptive errors when we're in production as well. All right. So, we can create locations, but now we want to actually list those out. So, as a traveler, I want to view a list of all my saved locations. And so, that'll be on the main locations page.
list locations in dashboard
Essentially, we're just going to have a card with each of those created locations and their title and description. So, while the page is loading, we should of course show a loading indicator. And then, if they don't have any locations, we should say something like click here to add a location. And then each location is going to show its name and description.
So, let's get back to the main branch. And then I'm going to check out a branch. This is story number 22. Now, if we head back into our app in pages, we want to display this when they're on the dashboard. So, in the app, when we're here, this is the dashboard page. When we're here, this is the ad page. So, if I want to display something in this nested route here, when I'm on the main dashboard page, I should create an index file. So, right now, the main dashboard page just has this nux page. But again, if we want to render something there, we're going to create an index.view. And just to test this out, let's add a template. And we'll add an H2 that says locations. And so now when you're on this page, we should see the index page.
When we're here, we should see the ad page. But this is what's going to list out all of the locations. So let's get this nice and styled. We're going to add a container element. And then we'll increase the font size of the H2 here. We'll just use text to XL. And then let's add a little bit of padding on the overall element. So that's looking good.
Now, we want to display a message that just says add a location to get started. And we'll put a nice little button right there. It's going to be a Nux link. It's going to go to the add page. And this will just say add location. And then we want an icon here. And the name is going to be tabler. And we'll go grab the same icon we were using earlier, which is this tabler circle plus field. And give it a size of 24. We'll give this a class of btn and btn primary. So that's looking good. Let's add a little bit of spacing between these. So here I'm just going to put this inside of container div. Make this a flexbox in the column direction with a gap of two. And then that makes the button really wide. So let's just give it some fixed width. So we'll just do let's say width 40. And then that looks good. But I just want to push this a little bit from the title.
So I'm going to give this a margin top of let's say four. Yeah. So that's looking much better. So it says add a location and get started. I click here. That takes me to the add location page. Great. But if there are locations, we want to list those out here as cards. So when this page loads, we need to request all locations from the database. So let's create an API endpoint for that.
So we'll head in here and we'll create a file locations.get. So if you make a request to locations.get, we're going to grab all the locations for that user. So I'm just going to copy this file, call it locations.get. get and then we can pull out most of this. So when you're getting the list of locations, we actually don't need to validate the body. We're simply going to query the database and then return that list of locations. But in this case, we do only want to allow loggedin users to actually list out their locations. But this is duplicate logic, right? We have this code right here and then we also have it right here. So I want to extract this out into a common spot so I don't have to write this every time I want to create a event handler that requires the user to be logged in. So for this I'm going to create a util. So in next you can create a folder called utills and then things you define in here we can use elsewhere. So what I actually want to do is define a function that allows you to pass in an event handler but only allows it to run if the user is logged in. So I'll create a handler called
create authenticated event handler util
define authenticated event handler and kind of wrap all of this. So here we'll call it define authenticated event handler.ts ts and it's going to need to do this. So, comment this out for now. This needs to export a function define authenticated event handler. And this function itself is going to take in an event handler so it can pass it to define event handler. So, if we take this code that we have before, we don't want to export it. We actually just want to return the creation of an event handler. And then if the user isn't logged in, it's going to immediately send back that error. But if they are logged in, then we can continue on with the request. So we actually want to invoke the handler that they pass in and pass in the event. So you can see here define event handler takes in an event handler. So we should also take in an event handler. We'll call it handler of type event handler. And event handler comes from H3. It's not giving us an
autoimp import, but we should be able to import event handler from H3 like this. And so now we take in that handler and then if the user was not logged in, throw an error. But if they were logged in, then we'll just call the handler that was passed in with the event that was passed in. And so now I have this nice composable function and I can use it in both spots. So if we head back over to locations.get, instead of having to do all of this, I can say define authenticated event handler and then I can do the work inside of here. And for now, let's just return an object that just says success true to make sure that it's all hooked up. But if the user is not logged in, it should return that 401 unauthorized message. So we can just test this directly in the browser because it's a get request. So if I try to head to API/loations, it returns success true.
But if I log out and try to go again to API/loations, it returns a 401 unauthorized. So the middleware is working. That's great. So now let's just replace it in our post route as well. So back over here we'll do define authenticated event handler import it in. Then I don't need to have this logic in here because it's handled in our custom utility event handler. But now we do have a type error because before TypeScript could see we had that if statement there. So it could tell hey you're making sure that user actually exists. Now it doesn't know because we've kind of indirectly changed that.
So what we could do is inside of define authenticated event handler override the type of this event here so that it has access to an event context where the user isn't possibly undefined. So to do this we will need to define a custom type. You can see that defined event handler takes in a handler where event is of type H3 event of event handler request. So let's create a new type here called an authenticated event and the base type is going to be of type H3 event. We'll have to import this in from H3 as well like that. Uh but now we need to override the context. So we can then compose the type. So we'll say that the context here is of type H3 event context that also is going to come from H3. But we're going to override that user type here to say that context do user is of type user. It's not possibly undefined.
So, if you remember earlier, we actually overrode this type here where we overrode the H3 event context and added this user to it. What I want to do really quick is extract this user type out so we can reuse it in other spots. So, I'm going to pull this out and just call it user with ID. And because that user is coming from better off, I'm going to define that user with ID type inside of my O file. So, this has all my other off stuff inside of it. So, let's also define the type user with ID. It'll be like this. We will pull in the user type from better off and then also export this. So now I have this type and I can use it in both spots. So over here we can pull in user with ID and then in our custom middleware we can also pull in user with ID. So now we have this type which represents an H3 event and then user is a user with ID. It's not possibly undefined. So instead of just directly taking in an event handler here, I can say that a handler is a
function that takes in the event which is of type authenticated event and then returns anything. And so now on the other side authenticated event is going to have that user and it's not possibly undefined. And then right here I can just use a type assertion that says hey I made sure that user actually does exist. So we can say as authenticated event. So now the types should flow through. And over on the other side inside of this handler, it should know that event.context user is defined because we validated it before the code even reached right here. So that's looking good. I'll just do a quick recap of what we did. So we extracted out this reusable event handler. We then defined our custom type here, our authenticated event. We then made sure that we are passing in that authenticated event where we make sure the user exists. And then over in our types file, we extracted out that user with ID so we could use it in multiple spots. So for any other API function that just uses the standard define event handler, user
will possibly be undefined, right? Because we're not checking to see if they're logged in. And so that's why we have the question mark there. But in our utility function, we're making sure that it exists. So any function that's defined in that way, it will be completely available. And then that user with ID was extracted over here to lib off.ts PS mainly because this is where all our better o stuff already is and so I wanted to define the type in there. So this is looking good. Now we can actually do the work of finding the locations for this loggedin user. So this function takes in the event and that's that authenticated event and then we want to find all the locations. So let's just say locations equals await find locations and we specifically want to find the locations with this user's ID. So we're going to pass in event.context context do user which isn't possibly undefined because we validated it id and then this find locations function we're going to define inside of our queries file. So if we head back over to db queries location in here we can export a function find
list locations API route
locations that takes in the user ID which is a number and then this can do the query. So here we're just going to return db.query.loation location.find mini where the location user ID is equal to the user ID that got passed in. And so this is a super simple query. We're using the OM like syntax just because we're doing a select statement here. And so this should find all the locations in the database that belong to that user. And so now back over here, we'll import find locations and then we can just return it directly. So instead of awaiting it, just look it up in the database and give me back everything that you find. And so this is our API method. It just pulls all those locations from the database.
And if we want to try it out, we can just sign in. And because we're signed in, our cookie is set. So if we head to API/loations, it reads all those locations that we created from the database. But now we want to actually call that endpoint inside of this locations page. So if we head back to our dashboard index in this component, we want to request all of the locations.
list locations in dashboard
So I'm going to add a script lang of TS and a type of setup. Now before when we were adding locations, if we take a look, we were just directly using the dollar sign fetch helper. And if you remember, this does have good type safety. So it knows about all of the endpoints that are available to us. But you typically want to use dollar sign fetch in response to a user event. So in this case, we're creating a a new location when the user submits the form.
So that's when we would use dollar sign fetch. If I want that data to be available when the page loads and you know that that request can happen at the top level, the thing that you should use is called use fetch. And so this is a hook that's built into nux that handles all the dirty work of actually loading that data on the server side and also hydrating it on the client if needed.
And it includes all of the headers of the request. So it's going to be making that request in the context of the user which is what we want because we want to list their locations. So right here I'm just going to say data is await use fetch which is built in. We don't have to import anything in and we get that same type of completion that we get with dollar sign fetch. And in this case I want to list all of the locations. Now use fetch also provides a few other values. One of them is status. So we can use status if the user navigated to this page on the client side. This would actually make the request on the client side and we want to show a loading spinner. So we can use the status variable for that. And then once the data is available, we can use the data attribute here. But the nice thing about use fetch is it will actually use the suspense API of view on the server side.
So when this page is loading, it's going to wait for this data to resolve and then actually server side render it with that data. So what we'll do here is if the status is pending, we are going to show a loading spinner. So I'll just have this div and we will show this if status is equal to pending. And then to show that loading spinner, let's just grab this large loading spinner from Daisy. Put that in there. And then if the status is not pending and the data exists, we'll render out that data. So we'll have another div here. And we'll say v else if data exists. For now, I'm just going to render it out as JSON. So I'll just add a pre here. We'll do a JSON.stringify of data with some spacing in there. And because I want to only show this if the data exists, I'm going to do v else if. And then if the data does not exist, I want to show this div here that says add a location to get started. So this will be our final v else. So if the status is pending, show the loading spinner. If the status is not pending and the data exists, show
the data as JSON for right now. Otherwise, if the status is not pending and the data doesn't exist, show this which says add a location. So if I've done everything correctly now on the page, we'll see those locations that got pulled from the database. Now this looks good, but there is some behavior we need to fix. especially if this endpoint takes a long time. What happens if we first serverside render, let's say, the ad location page. So, I'm going to do a hard refresh, meaning this is the first page that was loaded. If I head back to the locations page, there's actually a slight pause before it lets the navigation happen because it's waiting for all of that data to load in. To really see it in action, let's actually introduce some fake lag here. So, let's just add a promise that we await. So, this is going to wait for two seconds before resolving the locations. And let's try again. So, we'll do a serverside render of the add location page. And then when I click locations, you'll notice that it doesn't navigate there until the data is fully loaded.
And this isn't the best user experience. So, we actually want to use an option called lazy. And that will give us a better user experience and actually show that loading spinner when we get back to that page on the client side. So, if you look in the next options, there is an option here for lazy. And what that means is allow the navigation to happen, but it's going to be fetching behind the scenes. So in use fetch, we can pass in lazy true. So back over on the page, going to pass in some options and say lazy is true. And now it'll navigate to the page before the data has actually resolved. So let's see it in action.
We'll do a serverside render of the location page. We'll head here. We see that it's spinning and then finally the data loads in. So this is the behavior that a user would expect. Now it's it'll still work when we serverside render the page. it's just going to take two seconds before the page even loads. So, if I try to go directly to the dashboard, you'll see that it's serverside rendering that data, right?
It took an entire two seconds before it finally returned the page with all of the data inside of it. So, if you have really long queries or there's any latency, you're still potentially going to experience that. But once a user has loaded your site, then they will see those loading spinners there whenever the data is refreshed. So, let's remove that fake weight there. But this is really the behavior that we want because otherwise your pages will just feel really sluggish, especially if for whatever reason there's database latency or API latency or whatever else. So now let's actually render these out into some cards. So the parent container here, I am going to make a flexbox and we're not going to do flex column. We'll do flex row so that way it wraps them around. So we'll do a flex wrap and then we're going to iterate over our data here. Now right now we're not getting good type completion. You can see the data type here is any. We do need to fix the types in our utility function that we defined earlier. So right now we're saying that this handler just returns the any type. We want the type to flow through. So we're actually going to make this define authenticated event handler
a generic type that just takes in T. And then instead of returning the any type, we will return type T. And so now the types should flow through because TypeScript will be smart enough to see, okay, what is the return type of this? Well, it's a list of locations. And so the return type of this is a promise with a list of locations. And so if we head back to our page now, when we hover over data, that type is actually flowing through, which is what we want. So we can get some good type completion when we're iterating over them here. So if data exists, this is a list of locations. So I'm going to have a card for each one. Give it a class of card.
And we want to repeat this. So we'll say V4 for every location in data. And so location is now an individual location with all of those properties. So I'll make this a compact card. And then inside of here, we're going to add the card body. So built into Daisy UI is card body. And then inside of there, we'll render out the location name. So we'll just do location.name. And then below that, we'll add a paragraph tag with location.escription. And then view is complaining because we need to add a key. So the key here is going to be the unique ID of each location. So location ID. So now if we head back over, we've got some cards for all the locations. Uh let's make them different than the background color. So for each one of these cards, let's give it a class of BG base 200. And so now we have some cards that are visually distinct. Let's add some spacing around these cards to kind of push them down from the locations. So for the container here, I'm just going to add a margin top of four. So that
pushes them down. And then because this is a flex box, I'll add a gap. So we'll do a gap of two. That looks good. And then now I want each of these cards to be the exact same wid width and height so it's consistent regardless of how many locations that I have. So I'm going to give it a fixed width and height on the card element itself. So let's go ahead and just format this. But let's give this a height of 28 and a width of 72. So now these are nice and consistent. Now we don't have any descriptions cuz I created them without them. So let's actually just head to Drizzle Studio and then add some descriptions. so we can see what they look like. So we'll save those changes.
And then if we refresh this, those descriptions should come through. Nice. So let's just work on the text sizing. So the title of each of these locations should be a little bit larger. So let's just give this a class of text XL like that. And then I actually will increase the height of these cards a little bit. So let's just go maybe with a height of 40. So that's looking great. Let's look at our checklist. So a loading indicator is displayed while fetching the data. An empty state is shown when no locations exist. We tested that, but I'm actually going to test it again by just deleting everything in the database and make sure that it it works as we intended. Um, we have click here to add the location.
Again, we'll double check that. And then each item shows the location name. So, let's just try adding another location. So, I'm going to add New York City, Big Apple. So, we'll add this. This should add it to the database, redirect locations, and then location should refetch. So, let's see. Yeah, look at that. It's listed out. So, that's the behavior that we want. Now, just to double check that this behaves the right way when there's no data, I'm going to go ahead and just delete everything from the database and make sure that that message displays if there are no locations. So, if we do a hard refresh and nothing is displayed here, but I think I know the issue. So, before we didn't have any type completion, so we kind of just did v if on the data, but data is potentially an array or null.
So, we only want to display this if there is data and the length is greater than zero. So here we'll say if data and data.length is greater than zero. And then if there is data but data.length is zero then this should render out. So we'll save that refresh. And now if the user doesn't have any locations it displays this. We can click add location. Let's add Denver. So we'll add it. We should get redirected back and it should be listed out. There it is. Nice.
And if we do a hard refresh that data is there as well. Sweet. So an empty state is shown when no location exists. So, this is looking good. I do realize we are doing all of this in dark mode, but because we're using like BG base and stuff like that. If we head into light mode, watch for the flashbang. Um, we can see that it's it's maintaining these styles, it's just in light mode, but I actually do think we should increase the background color of these cards. So, instead of BGS 200, let's do BGB 300.
It's a little more distinct, and it's a little more distinct whenever we're in dark mode as well. Okay, so this looks good for now. I'm going to commit it all, push it up, deploy it, all that good stuff. All right. Next up, we want to show locations in the sidebar. So, loading indicator is displayed while fetching data. Location list is displayed in the sidebar. Each location shows name and icon. The list updates automatically when locations change. And empty state shows when no locations exist. So, essentially right here between these two buttons and the sign out button, I actually want to list out all of those locations. So that way when we have a lot of locations eventually we'll be able to click them from their cards or click them in the sidebar as well. So if we look at our architecture right now the page that actually has the sidebar is dashboard.view. So dashboard.view is this sidebar and then our main page gets rendered inside of here. So we need some way to let this component know about data that is set inside of like a nested page. So inside of here I want to be able to set those
list locations in sidebar
sidebar items once I have that list of locations. And so this is a perfect use case for another store, right? We can have a store that keeps track of what sidebar items should be added and then the dashboard can just read from that store and list them out here and then any other page that wants to set them can set them when needed. So let's head to the stores directory and we're going to create a new store called sidebar and in here we'll export it. Say use sidebar store and this will be define store.
We're going to call it use sidebar store. And then we can pass in our function which is going to define all the state that we need. So this store is going to keep track of a list of sidebar items. So let's just call this sidebar items. And this will be a ref that starts off as an empty array. But we want to give it a type. So let's define that. We'll call this a sidebar item.
And we'll export this as well. And a sidebar item is going to need a label, which is a string. It'll need an icon, which is also a string. and then also an href. So if it needs to link off to somewhere, that will be a string. And for now, the href is just going to be optional. And this needs to be of type, a sidebar item array like that. So this store is just going to return an object that has sidebar items inside of it. So now everywhere else has the ability to set those sidebar items. And for now, we're just going to directly update this list from inside the main dashboard page when we have that list of locations. So if we head back to pages and then our dashboard index in here, we're going to get access to the store. So we'll say the sidebar store is use sidebar store.
And then we want to set the items to be all of the locations. Now data is a reactive variable because if you remember when we navigate on the client side, data could actually change. So I actually want to have some sort of effect that watches for changes here and when it has a value set the sidebar store to have those items inside of it.
So for this I'll use a watch effect and it's just going to listen for data. So inside of here we want to check to see does data.value have something inside of it like did we get something back from the API and then if we did we can set sidebar store sidebar items to be data.value domap. So, we're going to map over all the locations and create sidebar items for each one. So, this gives us each location. And then we want to return an object that has a label, which is just going to be location.name.
And then it also needs an icon. For this, we're going to set it to be a tabler map pin. Let's go double check that. If we head to icons and let's just search for pin, we want something like this. So, yeah, let's do map pin filled. And then for now, the href of everything is just not going to go anywhere. Eventually, we're actually going to build the location page, but for now it goes nowhere. So, when this page loads, it's going to get that data. Once it has that data, it's going to set these sidebar items. Now, let's actually display them in the sidebar. So, if we head to the main dashboard, which is the parent view here, we can use the same store. And then below here, we can have a section where we iterate over those sidebar items. So, I'm going to add one more divider. And then below the divider, we'll iterate over the items.
So we essentially want to create a sidebar button for each of these sidebar items. So we'll iterate over to get each item in sidebar store sidebar items. And then for each one we'll pass in all the stuff. So label is going to be item label and then the icon is going to be item icon and the href is going to be item.href. So we're just passing through each of those things. Now we are using a v4 so we do need a key. So let's actually add that to our type. So back over here. So for sidebar item, let's also take in an ID which is of type string. And then whenever you specify these, you can add your own unique ID.
So that way we can use it in the key. So in here, whenever we're setting them, let's set this ID to be equal to location dash and then pull in the location ID. So location- one, location-, etc. So that looks good. And then when we're over here, we can actually pass in that key. So we'll say the key is item ID. Yeah. And right now we specified href as being optional.
Let's remove that. So so the type stops complaining because we are passing in a uh a default option here. Now because we already extracted out that sidebar button earlier, we can just pass in that same show label prop. So that way whenever we collapse the sidebar, it'll behave in the same way as all of the others. So if we did this right now, we should see our locations here. And we can see that it it has the same hover state because we're using that sidebar button icon. And if we collapse, it collapses and has the nice tool tip. So we did a good thing extracting that out earlier. So if we look back at the issue, so we are listing the locations in the sidebar. They all have a name and icon. Now we definitely need to show a loading indicator because otherwise this sidebar area is just going to instantly pop in instead of displaying to the user that something's happening. So let's actually handle that in here when we set the sidebar items. So I actually want to have a sidebar loading state. So if we head back to the sidebar store should have another state variable in here
where we can say that it is loading and then render out some sort of loading indicator. So here we'll just say loading it's a ref. It starts off as false and then we'll make that available. And then when we're setting the sidebar items here we'll say if data.value is a thing we'll set sidebar store.loading to false and then set all of the items. And if it doesn't have anything then we're going to set loading to true like so. And now back in the dashboard, we'll take that into account right here. So if the sidebar is loading, let's actually show a skeleton loader. So in Daisy UI, they have these little skeleton loaders. So it displays that something's going to be here. We just don't know what yet. And they have a nice little class for this called skeleton. We can give it a height and a width, and it'll just render out there.
So instead of displaying a loading spinner, it'll just be like, hey, some content is about to appear right here. So inside of here, I'll have that skeleton loader. And we only want to show this if the sidebar store.loading is true. And then for all of these items, I only want to display them if sidebar loading is false. Now in Vue.js, you actually will get a warning if you have the llinter enabled if you try to put a VIF on a V4. Now technically this will work, but the proper way to do this is to give it a wrapper element. So that way the wrapper element is hide and showed instead of the repeated elements.
So, we're actually going to wrap this in a div. We'll make this a flexbox, flex column, and then we'll say only display this if the sidebar is not loading. So, now when we refresh the page, it displays, but let's do that thing where we make the API take a little bit longer so we can actually see how this behaves.
So, in here, when we list the locations, we're just going to wait for 2 seconds first. So, if I head back here to the add location page and then I navigate to the locations page, you can see that we had that skeleton loader and then it pops in. Now, you can see some weird behavior here where like if I navigate away and then navigate back, this is showing the loading spinner, but the sidebar isn't. And that's because inside of our index dashboard page, we are taking to that into account where if the status is pending, we only show that and we don't display the data. So really what we should be doing is listening for if the status is pending and if it is then we set sidebar store to loading. So instead of having this else statement here we're just going to set this directly to set sidebar store.loading is equal to if the status value is equal to pending. So if status value is equal to pending loading will be true otherwise it will be false. And so now it's going to stay in sync with the UI. So, if I head away and then navigate back to this page, we can see that they're loading
again and then it pops in. Now, I do want to add a little bit of padding there. If we look in the Daisy UI example, they have a wrapper element. So, let's actually do that cuz the wrapper element can then have spacing inside of it. So, we'll create a wrapper element for our skeleton loader. Throw the v if on there. Put the skeleton loader inside. Give this a class of padding x of four. And then that should render the skeleton inside of it. Yeah.
So, that looks good. So now it's not taking up the full area and I'm curious what it looks like whenever we're in the collapse mode as well. So if we head back here, that looks that looks decent to me. So that loading indicator is displayed when data is being fetched. Uh now we should check does that list automatically update when the locations change. And it should, right? Because we did create this effect here that if the data changes, it should set the sidebar items. But let's double check. So let's go add a new location. So I'm going to add San Francisco. We're going to expect that we get navigated to the page. This shows as loading and it shows loading on the other side. So, we'll do this. Yeah, that's what we want to see. And then San Francisco should pop up. And then I have access to them in both spots. Great. So, that looks good. But what does it look like when there are no locations? So, we need to handle that as well. Let's head to our database and delete everything.
So, we'll delete both of these and refresh. And so, this isn't great because it's just completely empty. So I think what I'll do is if there are no sidebar items because in this case it's an empty list just don't display that section at all. So on dashboard view we are only going to display this if sidebar store sidebar items.length has a value and we'll do the same thing with this divider here.
So only show that extra divider if it actually has a length or if it's loading because you might have noticed that when I head back over here it displays that skeleton loader. So we do want to display the extra divider if sidebar store.loading is true. So if we're loading or it has items. So by default that section disappears. But if I ever head back to this page, it tries to get the data and then just displays add a location here. So that is good behavior to me. So let's go ahead and add a few more locations. And so this looks good.
But you might have noticed one issue. If a user were to navigate directly to the ad location page, so let's do a hard refresh. that locations page hasn't loaded. So, it's not actually setting the sidebar items. And we potentially want that want that, right? Because if I head back to locations, that sets the sidebar items because this is where we're requesting the data. And then if I head to add a location, they still exist there. So, I want this list to appear even if I navigate directly to the add location form. Now, to do this, we're going to have to lift some state up again. So right now, all of this logic for getting the list of locations and then adding them to the sidebar is inside of this nested route. And this code will only ever run if we at least visit this nested route first. But I essentially want to do all of this when the page loads. So because of this, I'm actually going to create a new store that handles all of this logic. And then we'll pull that store into this main page here. But that store will always be running in the background. So even if we don't visit this page first, that data will still be requested. So in the
stores folder, I'm going to create a new store called the location store. We'll export a store and then I'm going to move all of that codes into here. So I'm going to grab all of this and then move it into the store here. Now one issue is we cannot have async await at the top level of this location store here. So we won't be able to await usefetch, but use fetch works without the await. So let's try just removing that and then exposing this data here. So down here, we're just going to return the we'll call it locations and that's going to be data and we'll also have the status and that will just be the status variable that we got back. So now let's use this location store inside of our page here so we can get access to it. So in here we'll grab the locations store. So we'll be use location store and then I need to get access to status and data. Now we could dstructure those values, right? because we are exposing locations and status.
But take a look at the type when I hover over these. These are just a serialized object. We want them to actually be reactive variables. So instead of dstructuring from a store, there's a built-in helper that will allow us to dstructure while keeping the reactivity. So here I can grab locations and status and I'll use the method store to refs and pass in the location store. So now I get access to this but it is a ref and I get access to locations which is also a ref. And so now I can use these values down below. So here we were calling it data but these are the locations and that should look good. So let's give this a try. Now the location store is making these things available. Let's see if that data is available on page load.
So we navigate here it's available. If we do a hard refresh it's available. So that looks good. Let's make sure that when we add new locations the data is refetched because it might not be. So, let's try. We're going to add New York City. Call it the Big Apple. We'll add this here. And it doesn't automatically reload the data. So, we're going to have to do that manually. But, if you take a look at use fetch, we're going to head back to the location store. It actually does expose a function called execute or refresh. So, now let's expose this refresh method. And so, now inside of here, we'll call refresh. And so, refresh itself isn't a ref because it's just a function. So what we can do is say when this component is mounted we can say location store.refresh we'll directly reach in and call that method.
So now let's give it a try. So if I load the page all of the data is there. Great. If I add a new location let's say we add Dallas Texas. So we'll add it. And now we navigated to this page. So we refresh the data and the data loads in both spots. So this is looking good. But we did this for that one specific scenario where we start at the ad location page first. So if I do a hard refresh here, look at that. The data isn't available. So really what I want is I want to call refresh when we're at the top level, right? When we're on the dashboard page. So that's exactly what we'll do. So we'll grab the location store and if we load the dashboard and we're not on the locations page, we should call refresh of the location store. So we're going to pull in the location store and then when the dashboard is mounted if we're already on slashdashboard this component is already going to call refresh. So we don't need to call it then. But if we're on any other page we do need to call refresh.
So inside of here I'm also going to get access to the current route. So there's a built-in hook called use route and that'll give us access to the path. So when the main dashboard is mounted we'll say if route.path path is not equal to slash dashboard meaning we're not on the main page then we should refresh the locations data. So we'll say location store.refresh and so that should handle whenever we're on dashboard/ad the main page here is going to load it's then going to load its child component which then loads the ad page but the data in the sidebar will be available because we refresh the data for locations. So now if I do a hard refresh here, we'll see that it loads and that location data is available. And so this is the behavior I want, right?
Cuz I I want it to behave the same way regardless of where I am. Essentially, that sidebar data is always available regardless of of what page I'm on. And so this is looking good. Let's remove that artificial delay in our API function because it should actually be fairly quick, right? If I navigate around, it's only a split second before that data comes back. And so in most scenarios, it's not going to just sit there and spin like it does with that artificial delay. Now, one issue I did notice, check this out. If we do a hard refresh here, there is a bunch of padding on these items here. And I think that's because the way the serverside rendering is working, it's not doing the correct diff because if I do a hard refresh on the homepage and then navigate, you'll see that these sidebar items don't have the padding. And I've noticed this issue with nux and whenever you're using a v else and a v else if in server side rendering because basically what's happening is on the server side it's rendering with that skeleton and it
has this container with padding of four and then when it loads on the client side the diff isn't exactly right and it's actually using this as the container for the sidebar buttons. And so the fix instead of using an else-f is just to use a v if. So we'll have to hardcode things in here. So if the sidebar stores cybar items has a length then display this element instead of using a v else. And now because it's not an else- if we need to check for loading as well. So we'll say if the sidebar store is not loading and there are items in the list then we'll display them. And so I've noticed this issue where if you're using a VL sometimes the server side render just doesn't do the diff correctly. And so now this should behave as intended. If we refresh there's no extra padding there. we can navigate around. Doesn't add that extra padding.
Looks great. So, if we head back to our story, we are showing that empty state and the loading indicator and everything else. So, this is looking good. I'll get it all merged in and deployed. Now, we're going to set up the map. So, for this, we'll need to install a map library, then install a component library that allows us to use map components with Vue and NXT. We'll set up our map styles, get that base map displayed on the dashboard, and then also make sure that those map styles change whenever the user toggles between light mode and dark mode. In the next story, we'll start actually adding things to the map. But now, we're going to get everything set up. Now, in terms of libraries, there's a couple of different routes we could go down. You could, of course, use Mapbox. So, they have a really generous free tier, and they provide a map JavaScript library, and you can find some view component libraries for it. But once you're past the free tier, you would have to pay a monthly fee. So what we're going to do is use a library called Map Libre. And this is actually an open- source fork of the Mapbox JavaScript library, but we
map setup
can use it completely for free and add it to our page. We just install it from npm. When you're working with maps, you also need a tile source. And that's one of the ways that Mapbox will charge you is you're pulling in their tiles from their tile server. Now, another tile source is a service called Map Tyler. And you can actually use Map Tyler in combination with Map Libre. And Map Tyler has a lot of styles you can choose from. If you check out their maps product, you can see all of these different ones. You could pull them in, but they also have a monthly fee. Now, if you want to dive deeper into this and learn all about the world of maps, I actually did create a video here on the Syntax channel that kind of dives into all of this. And what we're going to use for our map tiles is actually this service called Open Free Map. So, this is map tiles that you can use. They're completely for free. And if you don't want to depend on their free service, they actually have instructions for setting up your own map tile server if you don't want to depend on uh their free server. So, what we're going to do is install this map library. Then, when
we need tiles, we're going to use open free map. And if you look in their quick start guide, they essentially just provide a tile URL and you can plug that directly into map libre. Now map libre is just a javascript library but it would be nice to have declarative components to work with map libre and that's where view map libre comes into play. So if you check out their docs essentially they provide view components like mgl map that under the hood are using map libre but when we write the code in our app we can just use these declarative components. Now we could use this library directly but there actually is a module in the ecosystem that adds all of this to nux for us. So if you look on the Nux docs, go to integrations and then modules, you can search for nux map libre and essentially they set all of this up for us. So we can use the view map libregl components in our app, but they add all of the autoimp imports.
So it works seamlessly inside of your nux components. So to get started with this, we'll head to the nux map libre docs. If you click on their quick start, they show you how to install it. Let's go ahead and check out a branch. So we're on issue number 24. We'll make sure I'm up tod date on the main branch and then we'll check out that branch. Okay, now that we're on that branch, we look in their docs. They give us a command we can run. We're using pnpm. So we'll do pnpm dlxy module add nux map map libre. And you'll see that this module also installs map libre for us behind the scenes. So this one command installed map libre view map libre and then also set it up to have all of the autoimp imports for us. And if we check out our Nux config, we should now have nux map libre there. Okay, the library is ready to go. We can now test it out. So you can see this is an example NX component.
set up nuxt-maplibre
They're just pulling in that MGL map and then setting a tile server on it. And one thing to note about these maps is that they are client side only. So these maps cannot be serverside rendered. So essentially what we'll do is we'll create our own component for loading in the map and we can put client in the name and that'll make sure that nux does not try to serverside render that map.
So we got the base map library set up and configured. Now let's go ahead and get the component library going and make sure everything works there. So what I'll do is I'm going to create a top level component called app map and this is going to load in that mgl map. But we'll essentially use this map anywhere else that we want in our app. And like I said, we want to make sure that this is only loaded on the client side. So in the file name, we'll doclient and that tells we'll allow the refactor, but that tells that this component should not be server side rendered. So let's just see if we can get their base example working. Throw this in here. I like to put this at the top. Set it to TypeScript. And now let's add this map component to our dashboard. So, if we head into pages and then dashboard, essentially what I want is I want the map to always be visible and I want it to be right below whatever we render out above. So, right now we're rendering out that list of locations. Right below that, I want to show the map. So, right here, I'm going to add an instance of
app map. So, that's the the map that we just created. And this takes up that whole area on the right hand side. So, I want each of these to take up 50% height respectively. So, I'm going to add height 1/2. So this is a Tailwind class that's going to add 50% height and we'll do that on both of those elements. Now let's give it a try. We head back to the dashboard refresh. And we are getting this issue that it can't find this export named scale control because in our map example, we are trying to bring in that navigation control which under the hood is using scale control. But if you check out the Nux Map Libre GitHub, there is an issue open and this user Dominic Marchelino is mentioning that we can add this setting here for Vit to optimize map libre and then it should be able to find that import. So let's give it a try. We're going to add this to our Vit section of our Nux config. So we head to the Nux config. We already have some VIT settings here, but we just want
to add some more the optimize dependency setting like this. So I'll save that. Our server restarted. It says it can't resolve it, but let's see if anything changed. So, let's do a refresh. We're still getting an error. I think I'm going to try installing map libregl directly because it is technically a subd dependency of nux map libre and maybe vit can't find it. So, if we head to the map libre docs, they tell us how we can install it. We can just do a pnpm install of map libreg. I'm going to kill my dev server. Do this and then let's try restarting. Great. And that actually loads the library in. So we're using nuxmap libre, but apparently vit can't find that dependency because before it was hidden behind nuxmap libre. But if we install it directly, then it's able to optimize that dependency. And since we did look at that GitHub issue, I did go ahead and add a comment for anybody if they're trying to fix this. We fixed it by adding map libgl directly as a
dependency. And that seems to work for now. Awesome. So we have a map here. Now, instead of this being 50%, I think I want it to take up most of the area. And then just this top area will take up only the space it needs for these cards. So, let's actually make this a flexbox.
We'll make it a flex column. And then we'll just do a flex one on the map. And that way it takes up as much space as it can. Like that. I like this. And right now, if we head to the ad location page, then it pushes it down there. So, we'll fix these styles in a bit. We'll probably make this like two columns, but we do want the map to be visible because instead of having to manually put in our latitude, longitude later on, we're going to uh make it so that we can just click on the map. So, we want it to be visible. Um, so this is looking good.
Let's head to our checklist. We have the map component library good to go. Let's get our styles set up. So, like I mentioned, we're using open free map. So, for this, for the light styles, we're just going to grab the liberty style. And then in our map component, we'll pass that style in like so. And now we should get a decent looking map.
map styles setup
It's going to take a second to load. There we go. So that's how great uh Open Free Map is. My network's a little bit slow right now, but Open Free Map now gives us that full map experience. We can see all of the locations and zoom in. Um so that's awesome. Now, this default Liberty style is more of a light mode style. Let's check out light mode.
Yeah. So this looks a lot better when we're in light mode, but when we're in dark mode, I want to have some dark map styles as well. And one of the nice things about open free map is it uses a specification for these styles. So if I actually go directly to this URL, it's just a JSON file that points to the open free map tiles, but has all of these settings that describe the colors of all the other areas of the map. Now, I've already done the hard work and created a dark mode. So, if you head to github.com/w3cjopenfreemap examples, click on the view example and then in the public styles directory, there's this dark.json file. This is a map style file that points to open free map but has some nice dark styles. So, we're going to use this. But if you want to create your own, there is a tool called map mapputnik mapnik. So, with maputnik you can open up a style. So, let's actually just point it at these map libre styles. We can throw the URL in there. It loads it
in, and you'll see this is that that default uh liberty style. Yeah. So, network's a little slow today, but they are in there. But once it's loaded in, you can go through and change all the styles. You can change the color of roads, the background color, the color of text, the size of text, all that stuff. And then that will result in a JSON file. You can click save and then just add that JSON file to your app. But we're going to use this dark mode that I have here. So I'm just going to grab this JSON. So if we head into our next app, we're going to put this in the public folder. So public will just serve up these files as is. They won't be processed by the bundler. And that's basically what we want. So in the public folder, I'm going to create a folder called styles. And then inside of there, I'm going to create a dark.json file and throw my dark styles in there. And now I can link to these directly in my map component. So let's actually create another style URL. That's just slashstyles/dark.json.
JSON. And just like that, we have some nice dark styles. And if you don't like this style, like I said, you can use a tool like Maputnik and modify them to your heart's content. Another tip I'll give you is if you do sign up for Map Tyler and then head into their dashboard, they have a bunch of different styles to choose from and you can actually look at their JSON files and potentially modify it to point to Open Freemap tiles instead. So if you don't want to do the hard work of modifying all the styles in map putnick, you could use one of the styles from map tyler as a base. But this is looking good. We have our dark styles here. But now we need to be able to swap out the styles based on the theme. So we've got our light styles. We've got our dark styles. We're showing the map on the dashboard. But now we want to change that style URL when dark mode or light mode is toggled. And if you remember earlier in the video, way earlier whenever we set up the theme toggle, we're going to do a very similar thing.
So the theme toggle is using that color mode module that we added. And essentially, we can just pull this in and then have our own computed value that's looking at color mode. And if color mode is dark, set it to the dark styles. If it's not dark, set it to the other styles. So that's exactly what we'll do. So in our map here, we're going to bring in color mode. And then we're going to set style to be a computed. And in here we'll say if color mode do value is equal to dark then we want to specify these dark styles.
Otherwise we will use that liberty style like this. And this should be all we need because this is automatically going to listen for color changes and then update the style accordingly. And then that style URL is actually bound to the map and it's listening for changes and should update the styles. So let's give it a try. If we toggle to light mode, look at that. We've got ourselves a light mode map. And if we go to dark mode, we've got a dark map. Sweet. So, all that's looking good. I do want to set up some sensible defaults here. So, you can see that by default, my map whenever I load the page is just centering here uh in in Europe and France. Uh but all of my locations are in the US. So, I'm going to add a default of the United States. So, the map just centers here. You can set the center to be whatever you want to be.
You also could potentially use the geoloccation API built into the browser. And if the user doesn't have any locations added, maybe you center the map on their location. I'm not going to worry about all that. I'm just going to center it to the United States. So, this is something we'll potentially reuse throughout the app. Whenever we need like a default location, we can just put it in the center of the US. So, I'm actually going to pull this into some constants. So, if we head into lib, I'm going to create a file called constants.
And then any variables that need to be reused throughout the app, we're going to define them in here. So inside of here, I have my center USA. I have the coordinates there. And this is what we're going to use inside of our map component. So we're going to go ahead and import in center USA from our constants. And now the map should center on the USA. It does. That's way too zoomed in. I kind of want to show it about here. So let's play around with this zoom level. So by default it's eight. Let's go with four. Yeah, that's looking pretty decent. We could even go even a little bit further out. And if we want to be super generic, I mean, we technically could just show the whole world. Um, but I'm thinking probably a zoom level of three is pretty good.
Yeah, this looks pretty good. Um, especially if the user doesn't have locations, but in the next story, we already have locations. So, once the page loads, we're just going to center this map around the locations that the user already has. This default is really just when the user first visits the app and doesn't have any locations to show on the map yet. Great. So, this is looking good. I'm going to go ahead and commit it, push it up, and we'll move on to the next story. All right. Next up, we want to actually show the locations on the map. So, as a traveler, I want to view all my locations on an interactive map. So, we'll show a loading spinner.
list locations on map
We'll zoom the map in to make sure that all of the points on the map are within view. every marker will be in the right spot and uh each of those markers is going to have a nice little icon. So, let's get back to the main branch. Pull in all the latest changes and then we're going to check out a branch with number 25. And now let's think through how we're going to do this. So, when we're on the main dashboard page here, uh we have access to all of the locations already, right? And each one of those has a latitude and longitude. So we want to provide that data to the map so that it can display some markers. Now I think the best way to do this is with a store right because we can have one centralized location where we keep track of which points should appear on the map and then that can be updated from any component because right now we want to show locations on the map but later on whenever we click on a location we want to show all the times we visited that location. So that'll be another set of points. So my thought here is we have a store keeps track of all the locations
that should appear on the map, the pins essentially. And then that can be updated at any time. So let's do that. We're going to head to the stores directory and we're going to create a store called map like so. And we'll want to keep track of a list of the points that should appear on the map. So let's head to the view map libre documentation and take a look at their marker. So in this example here, they have the MGL marker and they pass in the coordinates and the color. And this is just using the default marker built into map libre.
If we take a look at custom marker, you can actually pass just a custom template. So this could be anything. It could be an icon that we pull from icons. It could just be a custom div. And I think this is what we want to do. So the marker would take in the coordinates and then any data we would want to display. So potentially we might have like a tool tip that'll display the name of the location. So for each of the markers on the map, we at least need the coordinates and then maybe a label. So let's create a ref for that. We'll call this map points and it'll be a ref that starts off as an empty array. Then we need to define a type and we're going to call it map point. I'm going to define this over here in lib types because we'll potentially need it in other spots as well. So we'll export type map point.
And then this will need a label. We'll just make that a string. And then we also need the coordinates. And you saw earlier that we created coordinates with an array of two values inside of it. This is one of the ways that map libre accepts coordinates. But we can also use just an object with latitude and longitude properties. So let's do that.
And so I'm going to create another type called the lat long item. And this will have a lat which is a number and a long which is a number. Now there is a type built into map libre that's similar to this but it's not exact. So we're going to define our own type and then later on this type will overlap with that type. You'll see once we get there but our map point needs to have a latl long. So we're just going to create a composite type that says a map point has a label and all of the properties of latl long item. Now because we're going to be repeating over an array, we're going to need a key because we're working inside of view. So I am going to give each of these map points an ID and we'll make this a number. So now that we have that type, let's import it here. And we want this to be a ref that is a map point array. Now this store will make the map points available. Now we just need to set them. So the one spot where we get access to the list of locations is in the location store. And if you remember, we have this watcher here. So essentially, we grab the locations from
the API and then once we have them, we put them into the sidebar. But in this exact same spot, we can also put them into the map store as map points and then we can iterate over those inside of our map component. So right here is where we want to set them. So let's grab the map store and then inside of here if we have a value, we want to say map store map points is data value and then we'll map over those locations and create a map point. So each one needs an ID that'll just be location ID. It also needs a label. This will just be location.name and then it needs that latitude and longitude. So location.lat location.l long. So this will create that list of points in the map store.
Now we just need to iterate over those on the map and show them as markers. So if we head to our map component. So app map here we can get access to the store and then inside the map iterate over those points. So we'll grab the map store and then we'll iterate over the points here. So we want to create an MGL marker for each of the items in that list. So we'll do a V4. We'll say point in map store.map points and then we are repeating. So we need to give it a key and that's why we gave it that ID. So here we can say point ID because we know that'll be unique amongst the locations.
Now if we look back in the docs, MGL marker takes in a coordinates prop. So we can pass that in and then we'll just pass in the longitude and latitude. So inside of map libre if you're passing an array with coordinates it's always longitude latitude. So we'll do point dot long and then point.lat. And this should be enough to show the points on the map. Let's give it a try. And there they are. Look at that. So now whenever we navigate to this page all of the points appear here.
And if we navigate away from this page and head back, we will see that loading spinner just like we did before. And then the points will pop up on the map as well. So now let's customize these points so they kind of fit the theme of our app. And in their docs, you can see that we can pass in a template and then specify what they should look like. Now I noticed when we were specifying this coordinates prop, we weren't getting any type completion. So like, so if you try just typing coordinates, it doesn't even tell you that it's available. This is another issue with that next map libre plugin. It's just not providing the types like it should be at this point.
Maybe when you're following this video, it might be fixed. But if I had to go back, I just wouldn't use this module. It would just install the libraries directly because if we install the view map libre library directly, we will actually get type completion. So let's go ahead and do that. So if I do a pmpp install of view mapap libre, which is what next map libre is using under the hood, and I reload my window here, now we do get some type completion. So at this point really the main thing that that Nux map libé package is providing is autoimp imports of these view map libre components. So I don't have to import them in but we can still use them. But you'll notice I'm getting a type error here that we will have to fix. And if we go back over here and attempt to pass in the coordinates we can see that we do get type completion.
So if you want these autoimp imports use nuxmap libre. You're just going to have to install those other libraries separately. If you don't care about autoimp imports, just don't even use nux map libre and then just install map libre and view mapap libre. So if we look at this type error, we can see that our cent USA constant is just interpreted as a number array, but it wants it to be a longlat like. So let's actually just do a type assertion here.
So we can say this as longlat like and then we can import this in from map libre. And now we're telling it, hey, this array isn't going to change. it is like this type that is just an array of two numbers and then TypeScript is happy about that there. Now the length of these attributes is actually getting a little bit long for me and if you remember earlier we set up a llinter rule to autofix this. We head to our ESLint config. We said that the max number of attributes on a single line should be three. Let's actually change this to two. And now it should auto format that. This will potentially change our codebase in some other spots but this is much more readable. And I think really if you have more than two attributes it should be wrapping. So since we did that, let's go ahead and just lint our codebase and see how many other spots would need to wrap. Yeah, it's a lot. So I should probably do this on a separate issue, separate pull request, but it's just me. I'm I'm the only dev here. So I'm going to go ahead and do a lint fix and that'll fix the line wrapping and all the other files.
But from here on out, it's going to be a little bit easier to read. So it actually wraps sooner than after just three attributes. Okay, after that detour, let's get back to what we were doing, which is customizing the marker. So, in the view map libé docs, you can see that we can pass in this template. So, let's grab that and we'll pass it in here. If we just save that, we're going to get a bunch of red dots on the map.
Yeah, look at that. But, we want them to look nicer than this. So, let's actually pull an icon from icons. That's just a map point. So, we do have like that map point filled. And honestly, I think that's what we'll use because then we can change the color to match our Daisy UI theme. So, let's grab the map pin field icon in here. Instead of having a div, we can just use our icon component.
The name is tabler map pin field. And then let's try a size of 24 like we have throughout the rest of the app. See this looks like. And so that's looking decent. Uh we could increase them a little bit. So let's go with a size of 30 maybe. I think I like that. And since we're using Tailwind, we can actually provide some Tailwind classes in here.
So if we apply a class, we can use all of the text classes from Tailwind. And we have access to things like text accent or text primary or text secondary. So all of these will fit with our theme. And now we're getting a llinter error because that does need to appear on the next line. But just like that, now it uses the color theme. And if we switch to light mode, you can see that that icon is just a little bit darker. Let's try with text secondary.
See what we get. It's pink. And here it's pink. I honestly I kind of like it. So this is looking good, but I would also like to show some tool tips. So just like earlier we set up these tool tool tips on the sidebar where it shows the name of the place. Let's do the same thing on these icons. So as we hover over them, it'll show the name of the place. So let's grab that tool tip from Daisy. And we want these to appear on the top. So it's going to look like that. And now we'll just wrap this icon in the tool tip. And we won't default to open. And now the data-tip can be the label that we passed in to the list of points. So we can bind data-tip to be point.l. And now when we hover over, look at that. We get some nice little tool tips as to what each of these are.
Sweet. So we're showing a loading spinner on the page already because we're grabbing those locations from the same spot as the list in the sidebar and on the main area. We're also positioning them in the right spots and we have icons for everything. But now I want to automatically show all of the points on the map. And so right now it is very convenient that all of the points I've added are in the United States. But what if I added something in Europe? When the page loads, we won't be able to see that. So let's just do that as an example. Let's actually add uh Amsterdam. And I was actually the MC at JSNation Amsterdam in 2023. So we'll add it there. And now you can see it appears on the map. But let's see what happens when the map initially loads. Yeah, it always has that default center of the United States and then we can't see that point over there. So, we need a way to automatically shift the map to show all of the points on the screen. So, built into map libre, which is the core map library that we're using, is this launch
center map on location bounds
lat bounds constructor. Essentially, you can pass in an initial latitude longitude and then extend that bound. So, we're essentially trying to build up bounds, basically a rectangle that surrounds every single point on the map. And that's what this is useful for. You could potentially do your own math to find like the top left X, top left Y, top right X, top top right Y, etc. But this class is exactly for that. And once you've created it, they also have this extend method where given a single latitude longitude, you extend it by another point that then creates a bounding box that represents those two points. So this is exactly what we need and essentially what we'll do is look over all the lat launch of the points on the map create a bounds that represents all of them and then apply that to the map. So we want to do this inside of the map store. Essentially we can listen for if this list of map points changes and if it does we will recreate the bounds
and then reapply it to the map. So here I'm going to use an effect and this is very similar to watch effect. So earlier, if you remember in our location store, we actually used watch effect, but I've been playing around with this and I actually noticed that watch effect is the reason that we're getting a serverside rendering hydration error.
And I've been completely ignoring this. But if you look in the dev tools, when we initially load the page, hydration completed but contains m mismatches. And what that means is the serverside rendered HTML does not match the initial render of the page. And after some debugging, I figured out that it's because this watch effect isn't running on the server. So, while we're thinking about this idea of hydration and effects, I'm actually going to update watch effect inside of the location store to just use effect. And this should fix our hydration error because effect will run on the server and this data will be available on the server instead of only being available on the client. So, do a refresh. Let's clear out the errors. There we go. And so, that gets rid of the hydration error.
And so that's why now in the map store I want to use effect instead of watch effect. So now whenever the list of points changes we want to create a new latitude longitude bounds. So we'll grab this and import it in. And this comes from map libé GL. And we essentially will start off with the first point that will be our initial bounds. And then we'll extend it by each one after that.
You could do this with a for loop. This is actually a good candidate for a reduce. So let's get fancy with it. So we're going to reduce over the map points. So we'll say map points.value dot reduce. This is going to give us our overall bounds and each individual point. And then we can do the reduce here. Now the initial value of the reduces which is what we pass in here will be a latitude longitude bounds. It is the first point in this list. So I'm actually just going to grab the first point. So let's just say the first point is map points value at zero. And now it's possible that there are no points in the array, right? So when the user first comes to our app and they don't have any locations. So I actually just want to break out early here. So if the first point doesn't exist, then don't try to create these bounds. But if it does exist, we can actually pass that into our latitude longitude bounds here.
Now, when we're creating a launch lat bounds instance, we can pass in the southwest corner and the northeast corner. And since we're starting off as the first location, the first location or first point is the southwest corner and the northeast corner. So basically we need to pass in the first point dot long and first point.lat and then pass that in again. So this bounds is literally a single point on the map but as we add other points to it that bounds will start to expand. So inside of the reduce we can then return bounds.extend extend and then extend it by this specific point. So we'll pass in point.l long and point.lat. So this will give us the overall bounds of all the points that are on the map. From there we want to actually apply these bounds to the map. And if we check out the view map libre docs, there is this use map composable which essentially allows us
to get access to the map anywhere inside of our app. Now, for our app, we literally have one map instance in the entire app. We don't have multiple. And it's possible that you might have multiple maps. And so, you can use this map key to say which of the maps do you want to get access to? For our purposes, we only have one map. So, we don't have to pass anything in and we don't have to specify a key. So, inside of my store here, I want to get access to that map with use map. And use map gets imported from view map librag. We will just call this map. And then after we have the bounds, we can apply those bounds. So if you look in the map libé docs on the map instance, there is a method you can use called fit bounds. You pass in those bounds and it will automatically zoom in or zoom out the map to fit those bounds.
So right here we can say map dot map. So the map variable is kind of like a meta instance that wraps the component and everything else. But map.m mapap is the underlying mapgl map instance and that will allow us to say fitbounds and then we can pass in our bounds here. Now all of this looks good but we're going to hit some errors. So let's experience them together. Yeah 500 server error and we get this error that says requested module map libéjl does not provide an export named launch lat. Now, this is a pretty cryptic error, but really what's happening is these two libraries, map libé go and the view map libé go meant to run on the server side. They do things that are specific to the client side. So, if we want to use them, we have to use a dynamic import so that they're not imported in our server side code. Now, the way that I'm going to handle this is with an init function, very similar to what we did with our off store. But basically, we'll have a
function that's async that we can call from inside of a component to do this stuff here. And essentially, we'll make sure that that init function only gets called on the client side by calling it inside of our map component, which is a client-only component. So if we want to dynamically import these, we can pull them out of here and then define them here. So we'll say const on both of these and then we say await import. So import is a keyword built into JavaScript ECMAScript modules that allows us to dynamically import a module. And we'll do the same thing for this like so. So now this function we only want to run on the client side. So we don't try importing or running this code on the server side. So I'm going to expose this method called init. And now we can call this from inside of our map component. So if you remember earlier we defined this map component and it is a client-only component. So because it's
called map.client, this component only ever runs on the client. And essentially what we want is whenever this map is mounted, we want to call that init method. So we can tap into onmounted which comes from Vue.js JS and then we already have access to the map store because that's how we're iterating over the points. But inside of here I can just say map store.init. And now this code will only run on the client side after that map component has been mounted. And this should fix our errors. And it does. And you can see that the map fits to the bounds. So now Amsterdam is actually within the bounds there. Now this isn't ideal because they're like slightly off of the map. But if you check the map libre docs, the fitbounds function also accepts some options and those options can specify padding. So fitbounds also includes the fly to options. And if we look at fly to, we can see that it has a padding option. So if we pass in some padding, whenever it fits the bounds, it'll make sure that these points that are on the edges are still visible. So
whenever we say fit bounds, let's pass in some options here. Padding, let's try 10. See what we get. Do a hard refresh. It's a little bit better now. They're like slightly more visible, but I want even more padding. Let's go with like 40. Hard refresh. Yeah, that's nice. The full points are visible. And I mean, we could go even more. I mean, it the the length of the tool tip is going to vary depending on our points, but yeah, let's go even more. Let's go let's be let's be weird with it. 60. Yeah, that is nice and usable. Sweet. Now, what's nice about the way that we've set everything up here is when I add a new point. So if I go to add location that is going to update the list of locations the list of points is dependent on that so it's going to update and then the setting of the bounds is dependent on the the set of points so it will update that too. So we should get some magic here. Let's say I add a point way off the map like in Japan. Now I've never visited Japan uh and or travel to it but I want to. So maybe we can even have like a a wish
list of places I would like to travel. Let's add Tokyo, Japan to the map. And because we've set all of this stuff up in that way, the moment it I come back to the locations page, the map should actually fit and include all the points on the map. So, let's add Tokyo, hope to visit here one day. We'll add the latitude, longitude, and hope for the best.
Wow. So, uh you can see that the moment I got back to this page, that effect ran because it saw there's a new point. It created a new set of bounds and it automatically set the bounds on the map. Now, this isn't ideal because this wrapped to the next line. So, I actually want to update the styles here so that it just does a horizontal scroll. That way, this list of locations never really interferes with the size of the map. So, first up, let's head to the dashboard.
And right here, this is a flex. And we actually did have flex wrap on there. So, we're going to do a flex no wrap. And so, that way they don't wrap anymore. This introduces quite a few issues, though. For one, you can see that the sidebar shrinks and then also we have this overflow of the container. First, let's take care of the sidebar. So, I want the sidebar to always maintain the width that we gave it. So, if we head to the dashboard here on the sidebar, let's say shrink zero. So, this sets flex shrink to zero. And that way, it'll respect the width that we're applying when it's opened and closed.
Okay, so that's better. Now, at least the sidebar always has the same length. Now, to prevent this overflow for the page content here, we're going to put that in its own div that always takes up 100% of the flexed area. So, if we then head to the dashboard, down here is where we're rendering out the page. And you can see that this is a flex one. But I want this area to have a calculated width and height. So, we're going to wrap it in a second div. So, we'll throw a div below, make this the flexbox, and then put the page and the map inside of there. And then we'll give this div size of full. So it's always going to take up its parent, which is a flex one. So that should be fine. But now if we do overflow auto on this flex one, that will prevent the scroll bars from appearing. And now we can make it so this horizontally scrolls. So you see right now if I start collapsing, these cards start to shrink. So we want to do that same shrink zero on the cards that we're displaying here. So each of these
is within the flexbox. We're going to set this to shrink zero. So that's great. But now you can see that we're still within the container. Now the page isn't overflowing, but it's causing this container here to overflow. So finally, we'll put overflow auto on this container. So this is the only thing that scrolls. And this gives us our desired behavior, right? So if it's if we're on a tinier screen, then we can scroll here. The map is still taking up the full area. We can collapse this.
That still looks good. And if we go back to full screen, this behaves as expected. Now, I'm not going to pretend that that didn't take me an hour to figure out there. There's definitely other ways to approach this, but this is what I settled on. So that way, we have this nice experience where this is always taking up the full width and height, and then only this area scrolls. Okay, so that's looking great. Let's look at our checklist. The map displays with an appropriate zoom level. We added a bunch of extra stuff in there just to make sure that our layout looks good, but this is looking great. Uh we are going to work on the add location page in a bit because obviously this is taking up too much space. But for now, this is looking good. We got points on the map. Nice little hover states. This is nice and scrollable. Let's commit this. Push it. Move on to the next thing. Next up, we want to show some pop-ups on the map. So, as a traveler, I want to click markers to view location details so that I can quickly access information about specific places. So, markers respond to hover and click events. Essentially, when we click them, it'll show a pop-up. Pop-ups show the location name and description. And
map popups
hovering a location in the sidebar or on a card zooms into that location on the map. So, if we check out the view map libre documentation, they have a section with marker with popup. And this is basically what we want. We'll style it nicely, but essentially when we click a marker, we want there to be a little pop-up window on it. And the way that we do this is just use the MGL pop-up component inside of an MGL marker. So let's do just that. We're going to get back to the main branch and then we'll check out a branch for number 26. So whenever we display a marker, we also want to show a pop-up. So that's here inside of the map. We have all of these markers. We have the template for the marker, but now we just need to include a popup inside. So here we'll do an MGL pop-up. And if we check their docs, that popup can just have HTML content inside of it. So let's throw let's say like an H3 with the label inside of it. So we'll
say point label and then we'll give this a class of text. Let's try 2XL. And that should be it. Let's give it a try. So now when we click an element, we get a popup. The styles are ugly and we probably want the text to be a little bit smaller. So let's do a text just Excel. Yeah, it's a little better. And then we'll also include the description in there. So below that we'll just have a paragraph tag that has the point. Which doesn't exist. So let's update our point type to also accept the description. So we'll head to lib and then types. This can have a description which is a string. And then in our store whenever we're creating these points we should pass in the description too. So the description will just be location.escription that uh but this is possibly null. So let's make it that way in the type as well. So we'll say the description can also be null. Okay. So now we're passing the description in.
We're rendering it out here. And let's only render this element if there is a description. And that looks all right. I'm curious if we head to light mode. Yeah, it actually does show up. So essentially, we're just going to have to modify the styles built into Map Libre to make it so that they work for whenever we're in dark mode. Now looking through their docs, they don't really expose any way to modify these styles except for the CSS that gets added to the page. So if we open up the dev tools, we can look at this popup and we'll see that it has map libre popup and then there's map libre pop-up content map libre popup tip. So essentially we can write some CSS, some global CSS that targets these directly and just applies different styles whenever we are in dark mode. So let's head to our global styles which are just in main.css. CSS and then we want to target that pop-up content. So this is the class name that we want and we'll target it like so. And essentially we want to conditionally add classes
override maplibre popup styles
whenever it's in dark mode. But because we're using Tailwind, we can actually use the at apply directive and then use any Tailwind classes that are available to us. And so the way we conditionally apply a class if we're in dark mode is with dark colon and then the class that we'd like to apply. So if we're in dark mode, let's make the text white. And then also if we're in dark mode, let's do a background of gray 800. So because these are global styles, it should apply to the content. So it definitely changed the text color, but it's not changing the background. So let's see what's happening. So if we look at pop-up content, yeah, we have prefers color scheme dark. The color is white and prefers color scheme dark background color grade 800. So this is actually being overridden by the default colors built into map li. We just need a more specific selector. And our whole nux app is living inside of idx. So let's just add that as a parent selector here. So the map libre pop-up content that's
inside of our next app should be styled this way. And now that should be more specific. And it is. Yeah. So I like this style here. Very good. Now the other thing I want to style is that X button there. Let's actually push it in a little bit. It doesn't look too great uh off to the edge like that. So let's find it. This is the map libre pop-up close button. So I just want to add some padding X to that. Now we are in post CSS. So we should be able to nest our selectors like this. And so we can also apply this. So the close button we want to apply some padding in the X-axis.
Let's just do a padding X of two. And that is much better. So it pushed the X button in. So this looks great. The only issue now is this little triangle here is the light mode color. And we need to fix that. Um, but the map is smart enough to change the direction, right? You can see that it switches to like a left triangle, a down triangle. And if we click this one over here, it switches to a left triangle, and um I think I said left earlier, but I meant right.
So, you can see that. Uh, and I guess if we also change the height, it'll become a bottom bottom pop-up like that. So, this one's actually a lot more cumbersome. Basically, we have to find the selector for every possible orientation and then change the color for it. So, let's try to find that element there. And it's under this popup tip. And if we look in the CSS, we have a pop-up tip, but then we have anchor top. And we're setting the border bottom color. So, we're going to have to get all the orientations. So, anchor top, anchor bottom, anchor left, anchor right, and change the border bottom color. So, I have done this hard work for you. Uh, you can just check the link in the description to for the code for this repo if you want to go copy it. But we have all the orientations now. So anchor bottom, anchor bottom right, anchor bottom left. When that's the case, we want to apply border top. When it's anchor top, anchor top right, or anchor top left, we'll want to apply border bottom. If it's anchor left, we want to apply border right. And if it's anchor right, we want to apply border
left. Uh, so I went through the process of finding all the orientations, figured out all these classes, and then we're doing the same conditional styling. So when we're in dark mode, set that background gray color. And with that, now the tool tips are in the correct orientation. And it works for top and bottom. And it should also work for left. And then it should also work for right. Like that. So that looks good.
Let's just double check that when we're in light mode, it appears correctly. That did not show up. Okay. So it's not happening for light mode. I think we'll have to try a different approach for how we target the elements. So instead of using the dark prefix here, we can actually just target the HTML element when data theme is dark. And so this should still remain a more specific selector. But if data theme is dark, then apply these styles. Let's see if this at least gets rid of the styles.
And yeah, so this gets rid of the styles in light mode. Except we do want to add the padding for that close button when we're in light mode as well. So this is one thing that we always want to apply. So that looks good. But then when we're in dark mode, yes, it makes it nice and dark. Okay. But now that we're in dark mode, we actually don't need all of these dark prefixes. So we can get rid of those. Clean that up. And now these styles will only apply when we're in dark mode. Awesome. So if we check out our checklist, they respond to hover and click events. And the pop-up shows the location name and description. Now hovering a location in the sidebar or a card zooms into that location on the map. and probably also highlights it on the map. So basically as I hover here, I want first let's just get the icon color to change. So as I hover, we'll add maybe like an accent class. So it adds like a green outline to the card and then change the icon on the map to also be that green color. And then same thing if I hover over a card up here, it
set selected location on hover
should highlight that point on the map as well. So first let's just get some state in our store that is the currently selected point. So, anytime I hover over one of these, we want to set the selected point equal to its latitude longitude. Same thing when I hover over the cards, and same thing when I hover over points on the map here. So, hovering over this should actually highlight those elements in the sidebar and the cards. So, first we need the state. So, let's head to our map store and we're going to have another state variable called selected point. And this will be a ref that is a map point or null because it's possible that no point is selected. Okay, so that state exists.
Now we'll expose it to the world. And now let's handle the cards first. So when we hover over the cards, we should set the selected point inside of our store. So if we head to the dashboard index, this is where we are creating all of these cards. And whenever I hover over one of them, we want to select that point in the store. So when we mouse enter, set the selected point to be this specific location. So we'll listen for mouse enter and then when that happens we'll grab the map store. Is it in this component? It's not. So we're first going to bring the map store into this component. And then here we can say map store selected point equals we have to create a point. So we have a location and it has all of these properties but this doesn't exactly overlap with our map point type because it has a name. It doesn't have a label. wondering if we just rename the property and the type to be name instead of label and then we
could just set it directly. Let's let's try that first because that will definitely make this a whole lot easier. So if we head to our types here instead of label, let's rename it. So you can press uh F2 to rename a property. We're going to rename it to name. And that should have changed it all over the place. So for one, if we look in here, it did not. So we've got some refactoring to do. We'll make sure that we use the name there. The tool tip will be the point name and the store is the other spot where where we were doing this. So here we need to set the name as well. But now I'm curious because all of the properties match up. Can we literally just set it to this? We can.
This is the beauty of duct typing in Typescript. So it has the idea that if the types overlap, they're not exactly the same, but they have some of the same properties, we can we can just set it there. So So that actually reduces the amount of code that we have to add there, which means on mouse enter, we should be able to set the selected point to just be the location itself because it has all the same properties. So we'll do mouse enter and we'll say map store dot selected point is this location. And it's happy with that. Okay, that's awesome. Uh and then also whenever we do a mouse leave we'll set the selected point to nothing. The other thing we'll do is if this location is a selected point then we want to give it a border color. So we're going to do a class binding and let's add border accent if this location is the same as the selected point. Now in this case we
can't just do a d like a direct triple equals comparison like we can't say location is equal to uh map store selected point. I mean I guess we can and I guess they all share the same location. So we could have this same logic in the sidebar and have this same logic in the map point because it all has the same source of truth. So that makes it really easy. Okay. Now let's also add a cursor pointer whenever we're hovering over this element. So now whenever we hover over the element, we'll also see a cursor. Let's try that.
Okay, so that's working. But it's not changing the border color. Oh, we probably need a border width. Yeah, we need a border width if we want the border accent to even show up. So let's do a border of two. So that'll give us a two pixel border. Yeah, by default it's white. And then when we hover over it, we can see that it turns green. So let's say if we are not the selected point, we're going to just do a transparent border. So, if we do border transparent, we'll say if we are not the selected point. Okay, nice. This is great. We're on our way. I have a feeling the logic over here is going to be very similar and just as easy. Now, I don't like that there isn't much space whenever we're hovering and that border shows up. So, let's add a little bit of padding below this list of cards here. So, we gave it a margin top of four. Let's actually give it a margin top and bottom of four.
So, margin Y of four. Don't like that. So, let's give each of these cards a margin bottom of four. Give it a little bit of breathing room. Yeah, that's nice. Maybe we'll try two instead of four. Yeah, that's looking better. Okay, so when we hover over up here, it's selecting that point in the store. So, that's great. Now, let's get the same thing working in the sidebar. And I have a feeling that the way we do it is going to be very similar. So, if we head to the main dashboard page that's actually displaying these menu items here, we have these sidebar items. And I think what we'll do is change the icon color to be that accent color if we are hovered over it. So, first of all, we can add that same mouse enter and mouse leave logic like so. But right now, our sidebar items don't have location information. Right? If you look at the sidebar items, they just have ID, label, icon, and href. So, let's update that
type so we can actually attach the location to it as well. And then we would be able to say item.loation if it exists. Otherwise, null. Okay, so we got some work to do. First of all, let's get the map store into this component here. So, we'll grab the map store. Use map store. Okay, so now it has access to that. But now we should add the location prop to this item type. So if we head to our sidebar store, this sidebar item can have a location which will be of type map point, but it can also be null. Okay, so that's great. But now when we set those sidebar items, we want to attach the map point as well. And that's happening in our location store. So here we're adding all of the locations. We should be able to attach the location just like that.
So now it has access to that latitude, longitude, and everything else. Okay, looking good so far. Now we want to change the icon color of this button if that map point is selected. So let's add a new prop to the sidebar button called icon color. And we want to set it to like text accent if this is the selected point. So we'll say if map store.se selected point is equal to its location, then we'll use text accent. Otherwise, just use the default color. So, undefined. Okay, we're on our way. Now, if we head to the sidebar button, we want to add that icon color class. So, sidebar button. Now, we also will accept the icon color. And this could be a string, but we want to be able to get some type completion. So, it'd be nice if we could do like text accent, text primary, etc. So, let's just add a few in here. So text accent, text primary, text secondary. These are all possible Tailwind classes. Um, we can add more
later if we need them. But now that we did that, whenever we're specifying it here, we should get some type completion like that. So yeah, text accent is what we want. And then let's actually use this icon color. So on the icon here, we just bind the class. So class is equal to that icon color. Like so. Will it work? I'll be very surprised if it works on the first try. Let's give it a try.
Look at that. So now when we hover over these, uh, it highlights that icon there. And now when we hover here, it highlights there. All right. You know, there's one last thing we need to do inside of the map where we're iterating over these markers. If it's the selected point, we'll change it to be that accent color. So let's head to our map. This is where we're displaying each of the markers. And this is where we set the color. So if this point is the selected point we want the class to be text accent otherwise text secondary and should be a simple class binding. So the class is if the map store dot selected point is equal to this point then please apply uh text accent otherwise text secondary. So text accent and that should be it. So now when we hover here look at that they highlight on the map.
Sweet. Uh, another thing is when we hover over these, they should also highlight the ones on the map and up at the top. So, honestly, it's the exact same code. Let's go copy that hover state. So, when we hover over this marker, the selected point is the point itself. And that did not work. Now, I'm curious if we're even able to pass in mouse enter or mouse leave. It might be possible that view mapap libre doesn't actually pass those events down. So, let's just do some logging. So on mouse enter, we'll just log mouse enter and see if that actually works. So yeah, this is not firing those mouse events.
I'm guessing view map libre just doesn't pass down those mouse events. So let's actually just try putting it directly on the marker because we do control this div here. So let's see if this does what we need it. Yes. Yes. So now when I hover over these, they highlight within the uh sidebar and also in the top area.
Okay, that's good news. Uh let's also add some hover state. So when we're hovering, we should show a little pointer icon so they know that they can click on that to see the pop-up. So this div here should have a on hover cursor pointer. So now the user knows that they can click these items. Beautiful. Isn't this great? This this is just a a great demonstration of global state. The fact that all the state is stored in one single spot and we can reference it from all these different places and uh the code is fairly simple to do that as well. Okay, this is looking good. If we look back at our checklist, uh hovering a location in the sidebar on a card zooms into that location on the map. So, let's also do that. Essentially, if we hover over one of these, I want to see a nice pan into that location and zoom in on it. And then when we're not hovered on anything, it should go back to the default state of showing all of the icons. So I think we'll just handle this in the map store. So if you remember, we already have a reference to the map inside of here with this use map. So
zoom to map point on hover
basically what we should do is listen for when selected point changes and then when it does we can zoom into that point using this map object here. So, let's actually have a separate effect that says if selected point is a thing, then we're going to zoom in to that selected point. And the way we can do that is with fly to. So, this is built into map libre. And essentially, you can give it some coordinates and it will animate zooming in or zooming out to the coordinates that you provide. So, we're going to use fly to. We look at the example. We can give it a center and a zoom level and a speed. So the center is going to be selected point dot value lat no long. Don't forget long then lat and lat. Um and I don't want this to have a question mark here because we know that it's defined. So we should be saying if selected point do value is a thing. Great. Uh in terms of
zoom level we'll play around with this. Let's just try like uh I don't know six for now. And let's not modify any of the other settings. Okay. All right, so that looks good. Just do a hard refresh of the page because sometimes uh when you add new effects, it's not listening. But moment of truth. Yeah, look at that.
Look at that. So now when we hover over it, zooms around. It's a little bit jarring. So we probably do want to reduce the speed. So here, let's just see what 2 gives us. That was the default. No, we want it to be even slower. Let's go like 08. What unit is this? Let's try 10. Can we go even more? So like 40. Cool. Okay, so this is looking great. But now, if we're not hovered over anything, we actually should show the whole map again. So, if we head back to the store, what we probably want to do is hold on to the current bounds. So, once we've calculated these bounds, we'll keep track of them. And then later on, if the selected point is null, we'll just fit to the bounds that we fit to earlier.
So, I'm actually just going to move this variable out here. So bounds is a launch lat bounds or null whose default value is null and then inside of here we will assign to bounds and we'll make it a let so that way we can assign to it and then in our other effect we will say if selected point value is null and bounds is not null then we want to fit the bounds with that same amount of padding.
And let's just go ahead and extract padding to a variable so we're not repeating it twice. So out here we'll just say padding is 60. Okay. So now when selected point is null, if we've already fit to the bounds before, let's fit to those bounds again. Moment of truth. Zoom in. Zoom out. Okay. Hard refresh. Zoom in. Zoom out. Nice. Zoom in. Zoom out. Okay, it's zooming in super fast. I do not like that. Um I think the speed actually wasn't working earlier. Let's go back down to like 0.5 and then do a hard refresh of the page.
Yeah. Okay. Uh, now I feel silly because I'm playing around with that value wasn't doing anything. Apparently, we needed to do a hard refresh to make sure that that latest code gets loaded in there. Okay. So, 0.5 is a little too slow. Let's go with like 08 hard refresh. Yeah, that's a little better. I'm liking this. Now, I will admit this is a lot of motion, right? So, the user as the user kind of just pans around, this thing's moving like crazy. So, it would be nice to have an option to disable animation. I'm not going to add that. I'm going to leave that as an exercise to you. But basically, you could tap into the prefers reduced motion if a a user has that set in their browser. Or you could have a settings page where they set that and then if that's the case, you do not zoom in whenever they whenever they hover over an element. I like the idea of selecting, but maybe zooming in is a little much. I think the other thing is what if we don't zoom in as far? Then it won't be in as jarring. So, let's just do a zoom level of let's say three. I'm liking that a whole lot. And actually
like if we don't specify the zoom value at all, it very likely will just keep the same zoom value but center it on the map. That is I think a better behavior because before it was probably way too much motion. I like that a lot. So yeah, let's not even specify the zoom. It's just going to use the default zoom. And then if the user had zoomed in a bit and you hover, it will zoom to that respective level. Okay, so this is looking much better not zooming in, but I'm noticing really big, really weird behavior whenever we hover on the map.
And I think it has to do with the fact that like we're opening the tool tip, which slightly like changes the location on the map. So I'm actually going to disable hover on the map itself, but only keep it for the sidebar because I think this is good for the user to clearly indicate what they're hovering over. But if I'm on the map already, I don't think we need to try and zoom in to that location. So in order to get that behavior, I think we'll just have a separate state variable. So whenever we hover over an element on the map, that will in turn trigger a updating of the selected point, but it won't zoom in or fly to on the map. It will only fly to if we're hovering here or selecting in the sidebar. So here's what I'm thinking. If we head back to the map component on mouse enter instead of directly setting the selected point let's come up with a method name like map store dot select point without fly 2 something like that that's that's nice
and uh nice and clear um and then we'll do the same thing but with null in that case. So let's go figure out how to define this select point without fly to and this is going to be a method that we expose here accepts in a point which is a map point and then I think we just have another state variable that's a boolean that says should fly to and then we flop it on and off depending on if this method got called. So here we'll have should fly to and it's a ref that starts off as true but if you select point without fly to should fly to gets set to false. So value is false then we just update the selected point then whenever we fly to we should check this value. So here we'll say if the value changed and if we should fly to it then we will fly to it otherwise do nothing and reset it to true so the next time it will attempt to fly to. Okay, so this is
looking good. Lastly, we'll need to make sure that we expose this to the outside world. So export that. Now let's give it a try. So when I hover, it's selected but it doesn't fly. But if I select these, it does fly. Nice. I I like that behavior better because it was pretty jarring when your mouse is on the map and things are moving around. But if I'm in the sidebar, I like the idea of like kind of bouncing the map around and then later on we're going to have separate pages for each of these locations. So it makes sense that it hovers it, we click it, and then it immediately zooms into that and then we'll show more markers for all the times that we visited that location. Cool. I think the other thing is we should display that tool tip whenever we're hovering as well. So when we're on the map, we can add the tooltip open class if this is the selected point. Now I'm also realizing we need to update the type here to accept null. So this accepts a point or null. And then we can add a class binding that says the tool tip should be open. So tool tip
open is a class provided by Daisy. And we want to apply that class if this is the selected point. Yeah, look at that. Love it. I don't know why I get so excited for this stuff, but it's happening. We're building an app. Okay. Uh, all of this looks good to me. I'm gonna go ahead and commit it, push it, move on to the next thing. All right.
drag marker to set location coordinates
Next up, as a traveler, I want to select coordinates by clicking on the map so that I can accurately record location positions. So, right now in our add location form, we just have the user manually enter latitude and longitude. Now, we're going to make it a whole lot easier and make it so that we'll have a marker on the map and we can drag it around and that will automatically update the latitude and longitude in the creation form. So, let's get this started. We'll check out branch TL27 like so. Now, if we check out the app right now, when you go to the location page, it takes up the the top area. So, what I think we'll do is make it so that when you're on the location page, it actually just shows on the side because then it's nice and vertical and then our map will take up the full area on the right. And this one will always be on the top. So, for this, we're going to head to the dashboard. And in here, we'll make this flex column if we're not on the add location page. So, let's just do a class binding here. And I want to apply the flex column class if the
route.path is not equal to slash dashboard. Now, we're kind of just hard coding this comparison right now. Later on, we're going to have other pages that we want to appear on the left as well. We'll update this accordingly once we get there. Uh, and if you forgot, route actually comes from use route, and that's what gives us access to the current path. So, with this, now when we're on the dashboard ad page, the form should appear on the left, just like that. And then when we're on this page, it appears on top. Awesome. So, now let's actually give this a little bit of padding so it's not buted up against the edges like that. So, inside the ad page, let's just do a padding of four. That looks a lot better. Now, let's make the background of the page be a different color than the sidebar because right now it's exactly the same. So, what I'm thinking is in the dashboard, this section here, which holds the page in the map, let's give this a BG base of 200. So, now it's slightly darker, but you'll notice it kind of lines up with the color of the selected item. And then when we go here, that lines up as well.
So, I like that. It's visually distinct from the sidebar. Now, let's get a marker on the map that we can drag around. So, if we head to our app map map component in here, we want to have a special marker. So, going to copy this. I could extract this to a component. I don't think I will. I think it's going to be distinct enough that it should have its own. So, we'll throw this marker here. We don't want to repeat it.
And we'll just default the coordinates to the center USA. So, that's that constant that we defined earlier. And then for now we'll remove all this extra stuff. Let's make it visually distinct. So let's just give this a text secondary. And then there will be no popup for this marker. Now right now it's always going to display. But let's see it. So yeah, if we do a hard refresh, we can see uh there it is. So text secondary was exactly the same as what we were using before. I completely forgot. So let's do text warning. So that way it's that much more visually distinct. So we'll do text-warning. And then let's also bump it up a bit to 35.
So that way it's visually distinct. Yeah. So now the user should know that this marker here is the one that they're adding. It's not the one that's already on the map. Now for the tool tip, let's just add some help text. So here we'll add the data- tip and we'll say drag to your desired location. So now when they hover this, it's like yeah, hey, that's what this thing that's what this thing is for. Sweet. And then built into MGL marker is a dragable prop. So, if we add the dragable prop, that should make it so that they can now drag this around on the map. Sweet. Now, I am noticing that as I hover over these pins, every now and then, it is zooming like it does whenever we're hovering over the sidebar here. And I don't like that. So, I think whenever we are adding a new location, we will be in, let's say, like edit mode, and that won't zoom and pan the map because that's a little bit disorienting. And we'll also use this edit mode or like disable animation mode to know that this dragable marker should appear. So, let's head to the map store and let's create a new ref called added
point. It's really the point that we're adding to the map, but we'll need to have some actual coordinates on there. So, we'll call this the added point. And then we'll expose it so we can set it. And then if the added point has a value, don't do any of this fly to or fit bound stuff because that means we're like editing the map right now. So, if added point has a value, just immediately return. That way it doesn't try changing the map. Now let's actually set the added point. So it starts off as null and then we want to put it on the map when we're on the add page. So if we head to the add page when this component mounts, we're going to set the added point to be a brand new point. So let's add an onmounted hook. And inside of here, we want to access the map store.
So let's get access to it. And when we come to the ad page, we will say the map store.added added point is going to be a new point. The latitude is going to be our center USA at one and the longitude is going to be center USA at zero. And then what else do we need? We need the description which is empty. The name is just going to be added point. And lastly, it needs an ID which will just be one because we're not actually using it because we're not repeating over it with a V4. Now, let's make sure we bring center USA into this component. And it doesn't like that I am using bracket notation on center USA because we are using this type assertion here. So we'll use a type assertion that just says this is a number number and then we grab the item at zero like so. Awesome. So when we go to this page added point is going to be set and then since we already have it so we already have the on before route leave and if we are leaving the ad
page then we're going to set the added point back to null. So that looks good. But now on the map, let's only show the dragable marker if added point actually has a value. So we'll head back to the map and here we will say only show this if map store.added point is actually a thing.
Okay, so let's do a hard refresh. So now we're on the ad page. When we hover, there's no zooming happening because we're in edit mode. But if we head back to the locations page, that marker disappears and it it recenters. If we head here, then that marker is visible again. Awesome. Now, I want to keep track of where this marker actually is.
So, anytime it's dragged around behind the scenes, that's firing off an event that lets us know the actual location, the latitude, longitude. So, we should tap into that and then update the coordinates of the added point in our store whenever it gets moved around. So, here on this dragable marker, there is an event that's exposed by MGL marker called the update coordinate. So this gets fired anytime those underlying coordinates are updated. And for now, let's just log out what we get. And inside of Vue, if you're dealing with events, you can actually just pass in dollar sign event. And that will give you the data here when you're doing it in line. This is really great for debugging. So with that, open up the dev tools and then drag this. There we go.
So we can see that it's passing us an object with longitude and latitude. So now we can use that to update the longitude and latitude of the point that's in the map store. So I don't want to do this in line. Let's just define a function that takes this in. So let's say update added point and we'll have our function here. Update added point takes in the location which is an object that's longitude latitude. We'll pull that in from map libre. And then let's log it here to make sure that that still works. And we're not getting a type error down here. So yeah, it's happy with that. But can I drag it around?
Yes, I can. And I get the locations there. So inside of here, we'll just say if map store.added added point is a thing, meaning it's it's not null. Then we're going to directly modify the latitude to be location. And the longitude to be location.logitude ng like that. Now, behind the scenes, as I drag this thing around, we have its actual long longitude latitude. Now, inside of the form here, we can tap into that and then just automatically update these latitude and longitude fields. So, if we head to the ad form, we essentially just want an effect, right? We want to watch and see when does added point change and when it does, we're going to update the underlying latitude and longitude fields. So, we'll have our effect and we'll say if map store.added is a thing, then use it to update the form. Now, built into validate, there is another method exposed here called set field value. And this is going to allow us to
directly set latitude and longitude. So inside of this effect we will say set field value. We specifically want to set the longitude and latitude. So longitude will be map store added point dot longitude. And then we'll do the same thing for the latitude. Okay. Moment of truth. Look at this. Vue.js is awesome.
I feel like it would have taken twice the amount of code to get this working like in React. I don't know. View is great. So yeah, look at this. We're automatically updating the longitude latit latitude. So, I think ultimately we're going to hide these fields from the user and then show them some text that says, "Hey, move that marker on the right." Uh, but this is great. This is fantastic. Um, so what do I want to add?
Let's actually add uh Seattle because I lived there and worked there for about 3 months one summer and I was living in the Cap Hill area. So, like like right right there, right near that park. So, we'll call this uh Seattle. Say uh lived worked here for 3 months one summer. Now we'll add it. That takes us back to this page. Seattle is on the map. This is awesome. Okay, so what we really want to do though is make this a bit nicer for the user. So instead of actually displaying these two inputs, I think what we'll do is we'll still tell the user what the latitude longitude are.
But I can't I can't actually see a scenario where the user would want to manually enter in a longitude lat latitude. We have a map, so they can just drag it where they want it. So now let's actually remove the latitude longitude fields here and instead we will just have a little description right here that says drag the marker to your desired location. And I think we'll actually put the marker in the text here. So that way it's a clear indication that hey you should be dragging that yellow marker. So right here we're going to add an icon name is tableabler map pin. The class here is text warning. See what that gives us.
Sweet. I think we want map pin field. We want this one. So that looks great. Now let's display the underlying latitude and longitude so they know that something is happening. And I think I'll do this with just some muted text right below that like truncates the latitude longitude. So let's add another paragraph tag. And right here, we want to render out the the current value of both of those. And there's another nice helper built in here to give us the latest values. And here, we want the controlled values because this is going to be the ref that's automatically updating behind the scenes. So, we'll use the controlled values to display the latitude and the longitude. And I think most people are used to seeing latitude, longitude. map libre just accepts longitude latitude, but this should be fine. And then let's give this a class of text extra small and see what we got.
So that looks great. I think we'll truncate this to like four or five decimals. Uh and we'll also change the color to be more of like a gray text. So let's do like gray 400. That looks all right in light mode. And it looks good in dark mode, too. So I like that. And let's give them a little label here that says current location. And then let's write a function that formats these to truncate their values. So right about here, I'm going to have a function called format number. Takes in a value that is a number. We will just use the two fixed method. And let's try five decimal places. And now we'll use this whenever we're rendering out latitude longitude. So format at number and latitude is possibly undefined. Yeah, I guess because the form when it first initially loads, it doesn't have a value there. So I am just going to allow us to pass in undefined into this function. So this is optional.
And if it is undefined, we're just going to return zero for now. So hard refresh. Yeah. So it starts off as 0 0. The map kicks in. And now we can drag it around and we can see that it it's truncating it. I'm really curious though. So like how how much precision is this? Like if I Yeah, even dragging it like a centimeter still updates the lat long.
So I think five decimal places is enough to show the user, but we'll still store the full latitude and longitude in the database. Okay, so I'm liking this. Let me go ahead and add another location. Make sure it's all working. I will add uh Orlando because I have been to Disney World a couple of times. Now, where is Disney World? I couldn't tell you. But we do have a story coming up that's going to let users search for places and then show those on the map. So, that'll be a lot easier, but let's see if I can do some some soothing here to find Disney World. I think it's in Buuna Vista. This is it, huh? Yeah, Epcot Monorail Station. Epcot is my favorite park at Disney World. Okay, so I'm going to add that. We'll call this uh Disney World. And this is a magical place, right? We add it. It's on the map. Nice.
So, let's take a look at our current progress. So, map click updates the coordinate fields. Yeah, in this case, we're we're dragging it around. Coordinates display in an appropriate format, right? So, we are showing the truncated coordinates there. So, the user knows that something is happening. The selected location is visually highlighted. Yes, it is with that nice yellow marker. Marker can be dragged to adjust position. So, that's looking great. Now, one issue I do want to fix is when the map loads here, you'll you'll notice if we go directly to this page, the point to be added is off to the left here. And then, especially like if I was on the locations page and then headed to add location, now it's off the map. So, I want to make it so that if this added point gets added to the map, then we should zoom in on that point.
center map on draggable marker
So, that way the the user has a little bit of context of where this thing actually is. So if we head to the map store. So what I want to do here is watch when added point changes from null to a value. So I only want to center and zoom in on this point when we add it to the map the first time. And inside of view.js there is a method called watch.
And we can pass in specifically what we want to watch. So here we want to watch the added point. And then we can pass in a call back. But what's nice about this is this callback gives us access to the new value and the old value. And we want to do this if the new value has a value and the old value does not have a value.
So it should only fly to that point when it first gets added to the map. So inside of here, we can then do a fly to and we're going to fly to the new value.l long and new value.lat. We'll also increase the zoom. Let's zoom in to about six. And then the last thing is we want to make sure that this runs the first time this value changes. So watch also has some options and we can pass in immediate true. So with that if we do a hard refresh now you'll see when you go to this page it zooms in to this point that they want to add. We head back to locations it zooms out. And then if we go to add a location it zooms in to that marker so they know that they can drag it around. Now we have one more issue.
You'll notice that if I haven't touched anything, I haven't even dragged the marker and I try to go back, it's actually detecting the form as dirty because we are technically updating that latitude longitude value. So, let's fix that. And really, all we need to do is tell the form that the initial values are the same values that we're specifying on the added point. And then whenever this runs to set those values, they wouldn't have changed. So, it's not going to mark the form as dirty. So essentially what we need to do is just grab this longitude and latitude and pass it into the initial values on this form here. So built into validate is an option called initial values and we can say that when this form loads up these are the initial values and then when they're changed to be the exact same values it won't be marked as dirty. Now I noticed a bug where if you want dirty to have the correct value you actually do need to pass in some initial empty values for both name and description.
Otherwise, dirty was not behaving as expected. So, we are going to pass in initial values for those as well. But now, if we do a hard refresh, if I don't move the marker, I can head back and it knows that I didn't change anything. But if I head here and I do move the marker, it will know that and say, "Hey, are you sure that you want to leave because you actually have changed the location of that marker." So, that's the behavior that we want. I think we're in a good spot. really thinking about user experience though, I kind of just want to show this tool tip all the time, right? Because the moment they go to this page, it'll be very apparent that they need to drag that around. So, let's do that. If we head back to the map component, I actually just want to show this tool tip all the time. So, we can add the tool tip-open class. And now it's always there. And I think this is a better user experience because it's much more apparent to the user that when they get to this page, this is the marker that they need to drag around. Okay, this is looking great. I have actually changed
my mind about some user experience here. Now, I am honestly I'm the more I use the app and the more that I work with it, I actually don't like that this zooms and pans as you you move around. You'll notice that like as I'm just trying to go to the ad location, it's like panning the map. I'm going to remove that feature. I I still like the fact that it highlights, but I don't want it to pan around when the selected point changes. So, I'm going to just go ahead and rip out that functionality while we're here because this is my app and um I don't have a designer. I don't have a user experience designer. I am the user experience designer. So, here's what we're going to do. If we head to the map store, I am going to yeah, just get rid of this. Should fly to select point without fly to. We're going to get rid of all that. We won't expose this anymore. And then I can just get rid of this entire use effect. So don't even listen for the selected point because we're not going to be bouncing around.
So I'll remove that. And then I'll need to head back to the map. And that method doesn't exist anymore. Select point without fly to. Here we will just literally say map store.edoint equals this point. And then map store.selected point equals null. And so now they'll still highlight, but it's not going to bounce around a bunch because that was actually very jarring the more that I use the app. So yeah, they still highlight and it highlights when you're here and then we can head over here.
Still a fine experience. I like it. Now, one last bit of functionality. Again, this is all about user experience, is I want to be able to just double click on the map and then instantly move the marker there, right? Cuz it might be a little cumbersome, especially if it starts here and then maybe they want to go way over here. Maybe you're already searching around the map. It would be great to just double click and then it instantly moves the marker to that spot.
double click map to set location
So, let's get that working. So we essentially want to listen for double click on the map itself. And they have an event. It's map colon double double click. And so this will get fired off if they double click on the map. So we're going to tap into this and we'll just say on doubleclick and essentially if the added point has a value, we're going to set its location to the doubleclick location. So we'll have our function here on double click. This is going to get the event. Let's just log it out for now to see what we get. Now we'll open up the dev tools. Double click. It's a type of double click. If we look at the event, we can see it has a launch latl lat which has a latitude longitude. So that's what we want. Now I want to get the right typing for this event. And you can see that the MGL map, they either aren't providing the correct types or just these types aren't flowing through.
But here is a quick way to try and find those types. So essentially all of these events are for the underlying map instance from map libre. So if we head to our map store, just go to a spot where we would have access to the map. just do like map.m map and then there is an on method built into the map and this is where you can pass in events and you can see map libre itself has good type safety so these are all the possible events we could tap into the one I want is double click and then I can see what is the type of that event listener and it's this it's a map mouse event so that's the type I want to use over on the other side so we don't have any changes here I just wanted to head there to get the correct type so this event is a map mouse event and we'll import that in from map libé g and now I should get good type completion as to event. La longlat etc. So inside of here if map store added point as a value meaning it's on the map we're going to update its latitude longitude to be event.lat and
event.lo. So now when the user double clicks the map it should move the marker. If I double click, it fails. Let's do some logging. I think the view mapap libre library is wrapping this event. So, let's log it and then confirm what we're actually getting here. So, double click. Yeah, it's a wrapped object. So, we have the object. It has a type, but then it has an event property that actually is the event itself. I'm very curious if this type here is exposed inside of View Map Libé. I'm going to go look at their docs. If I don't find anything, we're just going to type this ourselves. Okay, didn't find it in their docs, but I went to their GitHub repo and uh honestly, this is an exercise you should try. If you are trying to figure something out, you can't find it in the docs, go to the source code, and it was very easy to find. So, in their git repo, they have a lib folder and then right at the top is types.ts. So, I was like, huh, maybe there should be something in here. And would you look at that exported at the top level is an MGL event. That's
exactly what we need. So, we will create an MGL event of type map mouse event. And we should be able to import this in from view map libre. And it looks like it just wants a key. It doesn't want the type. So, will this give me some type completion? Yes. Okay. This is the way to go. Um, I'm actually surprised I didn't see this in their docs. I might make a PR after this video because yeah, you search for MGL event, you don't really see anything. So, yeah, I'll probably PR to to add this to their docs. But, this is exactly what we need.
And now I get good type completion. So it's eventevent. Yeah. And honestly to be clear, let's call this the MGL event. MGL event.event. Great. So this is the winner. Now back to the site. Hard refresh. So now if I double click, doesn't work. There's one more thing we forgot about. And honestly, the code is kind of getting a little hard to keep all in your head at this point. But we are setting latitude, longitude, and expecting that that marker on the map is just going to update. But if you remember, we actually just initialized it to center USA. So instead of doing that, we need to make sure that it's using the coordinates of the added point. So here we'll pass in map store.addedpoint launch app store.addedpoint.lat. And this hopefully will be everything we need. Hard refresh. Double click. Yes, that's what we want to see. So if I zoom out, pan over here, and then double click. Boom.
It instantly moves the marker to that point. Awesome. Uh let's also update the help text so the user knows that they can do that. So back on the add page, we will say drag the marker to your desired location or doubleclick on the map. Let's put or double click on the map to be its own paragraph so it has some nice spacing. Double click. Nice. All right.
Looking good. Now, if we look back at our checklist, all of this map user experience stuff was just something I wanted to do. I didn't have it as success criteria because ultimately I mean there's a lot of different ways that the user can interact with the map. So by the time you watch this I might add a few more points here but this looks good for now. Let's commit it push it move on to the next thing. Right.
places search api options
Next up as a traveler I want to search for coordinates by address or place name. So we just made it so that they can move the marker directly on the map. But it would be nice if you could just type in a search like Disney World or Casabonita or Tokyo Japan and then that instantly popped up on the map. So, for this, we're going to need to talk to some API and we'll get that set up and then talk to that API to show a list of search results and then provide a way for a user to say, "Yes, that's the one that I want to use for adding this location." Now, for APIs, you have a lot of options. There is, of course, the Google Maps Places API. However, it does require the Pro plan. So, you already have to have your credit card down and have a paid account. But, if you have that, you can get up to 5,000 API requests per month for free. Um, but you can see it gets expensive pretty quick.
Um, there's also the Mapbox searchbox API. And so if you're already using Mapbox, they actually have a component that you can just directly add to your map and it'll use this. But they also provide an API directly. So you can just integrate with it however you want. And this will let you search for points of interest by name and you get 50,000 requests per month for free. So pretty great. There's also Map Tyler. So we talked about them earlier. They also provide hosted map tiles, but they have their own search API and this gives you 100,000 requests for free per month. So, if you're looking for like a fullfeatured API, map Tyler is probably the cheapest. I would say try out the free tier on all of these and see if you get the results that you want because not all points of interest are included in every one of these APIs. Now, for our purposes, I'm actually just going to use a free and open- source geocoding and place search API called Nomenatum. And it's actually from the same people that brought you Open Street Map. And if we're talking about all of this, the map
data for Open Free Map, which is what we're using, actually is provided by Open Street Map. And Open Street Map is kind of like the Wikipedia of maps. Uh, essentially anyone can go to Open Street Map and add a new location or make updates if like a road is closed or maybe a road doesn't exist anymore or maybe like a new city got added.
Basically, anyone can go on Open Street Map and add that data. And then all of that data is what Open Free Map is using to give us their map tile data. And so with that, nomento is essentially the database of all the places that have been added to the map that you can use and search with. Now, this is just for occasional use. Definitely read their usage policy because it says you should not and let me turn on dark mode. It says you should not use this for things like autocomplete. So unacceptable use is autocomplete. You should not send a request to their API on every single key press. They also say things like systematic query. So if you're trying to scrape for like postcodes and towns, don't use it for that. And then they actually have a hosted version of this.
They say don't scrape that page. Basically, this is a free service they're providing and be nice to it. So, a max of one request per second. Provide a user agent so they know where that request is coming from and then add an attribution to your page. So, this is what we're going to use because the user experience I want is essentially we'll have like a search area down here, but the user will have to fully type in what they want, click enter. We will then show the search results and that's going to be way less than one request per second because it's going to take a user a lot longer than that to like search for a new value. So that should be within the usage requirements. And this is going to work fine for what we have here. I will say having worked with nomenatom, they don't have as many points of interest as like you would get with the Google Places API or some of these others. Like these other ones include like restaurants at the city level, right? You can search for like Chipotle and get a list of every single Chipotle in Colorado. NomenAdam does not have that fine level of search, but it does have bigger points of interest like Kasab Bonito or Disney World or
Disneyland. Um, or you can search for cities or countries. So, this will be enough for our use cases. Hello there. If you've made it to this part of the video, you've found a secret spot sort of. So, the runtime for this video on YouTube couldn't be more than 12 hours long. So, I actually took this section of the course where I was working on this feature and it's a separate unlisted video that's linked in the description. So, click that link if you want to see me walk through this next feature. Also, if you want to take a look at the code for this feature, if you look at the commit history on the GitHub repo, there is this commit here called add location search. It has this commit ID that starts with A63A1D. And this has all of the files that were changed when I worked on that specific feature. But like I said, if you want to see me walk through this, there is a link in the description to the unlisted video. I just couldn't fit it into this video. Um, and if you made it this far into the video, thank you.
place search
Thank you. And and um yeah, thanks. Thanks for watching. Hopefully things are good. Uh, comment banana down below if you actually made it to this part of the video. Okay. Uh, so that's it. That's enough of me. After this, it'll be the next feature. But again, if you want this feature, it's in that other video. Okay, bye. All right, next up, as a traveler, I want to view details about each location so that I can recall specific information about places. So, right now, we just have kind of this top level view of all of the places we have visited or would like to visit. But for each one, we need to be able to add the times that we visited. And we'll be able to add multiple times. Like, I've been to lots of places in Denver multiple times, and I've been to New York City multiple times. So, I want to log each of those. But before we can do that, we need a page specifically where we can manage that one individual location. So, I should be able to click on a card or click in the sidebar or when I open up the pop-up here, there should be a button that says like view and that should take me to the page specifically
view location page
for that location. So, I can then start adding logs to that specific location. And that is exactly what we will do. So, let's check out a branch for ticket number 30. And essentially we need a page for locations. So in the dashboard I want the URL to be dashboard slug. So in dashboard I'm going to add a folder called location.
And then inside of there I'll create a file using brackets. So we'll say bracket slug.view. So brackets are how we say we're going to have a param in the URL. So we can grab that slug out of the URL. For now, let's just add a header that says location page. And then let's make it so that when we click on the cards, they take us to this page. So in the index, when we're listing out the locations here, essentially, I want each of these to be a next link so that it can take me to that page. So each of these cards now just needs to be a next link. So I'm going to change it from a div to a next link, like so. And then we can tell it where to go. So here we'll bind to two and then we can specify the name of the route we want to go to. So this is dashboard location slug and in here we can pass in a name and we can just use that path. So if we say dashboard-lo that's going to take us to
that page and then we can pass in some params and in this case we want to pass in the slug. So here I can say params it's an object and the slug should be location. slug. So with this now when I hover over the cards they should specify a link. You can see in the bottom left there. So location New York City and when I click on it that takes me to the location page. So this is what we want. Let's also get this working in the sidebar here. When I click these it should take me to that location page as well. So if we head to the dashboard where we list out all of the sidebar buttons. Now, for these sidebar buttons, I want to be able to use the same to syntax that I used on the cards, right? I want to be able to say to and then specify the name. It's a lot easier than trying to construct a URL like with paths. So, I think we'll adjust the type to allow us to pass in a two object as well. So, if we head to the sidebar store, this is where we define the type. And I also want to be
able to specify a two. And this will be optional. And the type here is route location raw and this gets imported from view router. So now we can specify two and then if it exists we'll bind that two attribute on the nux link and then we'll also make href optional. So that way you can specify either or. Now whenever we create the list of sidebar items this happens in in the locations store right we're setting right now the href to this but instead we want to specify a two and we should get some type completion now like for the name attribute etc. So if I want to reuse that same one we want to go to dashboard location slug and then the slug will be location.slug. So now I can specify that there and then we just need to make sure we use it in our sidebar button. So if we head to our components sidebar button this should now also accept a two attribute. So href will be optional two will also be optional and this will be a
route location raw and then on the nux length and then on the nux link we'll specify props.href or props.2. And now for these sidebar buttons we're going to pass down to instead of href. So item.2. And just like that, these should now link to the right spot. And they do. Awesome. Now, I updated a lot of types in here. I want to make sure that I don't have any more type errors. Like, I don't have any spots where I was depending on the href or anything like that. So, let's just run a type check. So, built into the NX CLI is this type check command. So, let's give it a try. We do pnpm dlxy type check. It will install VueTSC because that's the Vue TypeScript package. And now we have some some type checking. Now I don't see any issues with like href or two, but we did discover a type error in a spot of our app that we didn't know about before. So this is good. Now this is probably something we should have done a whole
typecheck npm script
lot earlier. But let's actually add the uh nuxy type check command to our package.json. So let's add a type check command. We'll just say nuxy type check. And then let's actually install viewtsc into the app as a dev dependency. So let's install. And now we should be able to run pmppm type check. So that looks good. Uh and then now let's fix our completely unrelated type error. So this is in server middleware off and it says yeah. So this was a while ago but if you remember we overrode the user here to have an ID that is of type number. Uh but the built-in user type here does not have that. So we actually can just do a type assertion. We'll say user with ID and we'll first cast it to unknown and then say user with ID. And I know that we can do this because we specifically are setting that ID type to number under the hood. So this was this was a a rabbit hole that we just went down, but like I said, we we definitely should have set this up a whole lot earlier
because now when we make big refactors like the one we just did, we're adding that that two and href property. We can check our whole codebase to make sure that we didn't leave anything off. Yeah. So that fixes that type error. Okay, back from that rabbit hole. Now, when we go to this page, we should actually show information about that specific location. So, on the location slug page, we need to get the current location and we have access to the slug. So, we should create an API route where we can send a git request to locations/lug and then that should give us back that specific location. So, here in the API folder, I'm going to create another folder called locations. And then inside of there, I'll create a file called brackets slug.get.ts. So when we make a get request to location/slug, this will run.
view location page continued
It'll be fairly similar to this one, except we're just getting one location by slug. So this will be an authenticated event handler. You can only get a location by slug if you're logged in as that specific user. And then we'll create a query function called find location where we pass in the slug and the user ID. and then we'll query the database accordingly. Now to get access to that slug, we can use a method built in called get router param.
We'll pass in the event and then the name of the param that we want is called slug. So we'll grab that. And this is coming back as undefined, but we'll never get to this route unless they've specified a slug in the URL. So we will say that this actually is a string. So we have the slug, we have the user ID.
Let's define this find location query. So if we head to lib db queries location we have find locations. Now we want a find location singular and this takes in the slug which is a string and the user ID. Now the query very similar to one we did earlier but instead of looking by name we will look by slug. So we want to find the location where the location slug is equal to this specific slug and the user ID is this specific user ID.
And then lastly, we just want to find first because since slugs are unique, there should be only be one location with this slug and this user ID. So if we try this out, let's go to API/loations/ San Francisco. We get back San Francisco. Awesome. But what happens if we pass in a slug that does not exist? We get back nothing. So we need to handle that. Essentially, if that location was not found, return a 404. So back on the API route, we'll grab the location. We'll await this. And then if the location was not found, we want to send back a 404 error. So let's copy our send error code. And in this case, it's a 404. And we'll say location not found.
Otherwise, if we did find the location, we will just return it. So now, if we try to make this request, it returns a 404. Awesome. Now, we can use this endpoint on our front end. So, if we head back to the location slug page, let's add a script. And I essentially want to grab that location with that slug. So, let's first grab the current route. We can use use route. And then we can use route.params to get the slug for this location. So, let's just say the slug is route.params. And then for now, let's just render that out here on the location page. Like so. So, we head back to the dashboard. Now, when we go to a location, we can see that slug there.
Awesome. While I'm thinking about it, let's just give this top area a height, very similar to the height of this locations page. So, here on the locations page, I'm going to give this a min height of 64. And then we'll do the same thing on the location slug. So, let's give this a parent container. And then we'll give it the same amount of padding. and that same min height. So now whenever I swap between these pages, that top area is always taking up the same amount of space. So now that we have the slug, we can make the request to our API to get that data. So to grab that data, we will say data is await use fetch and then we want to call that locations/slug endpoint. Now we will have to construct this URL and then we'll pass in the slug there. Let's rename data to location uh and then we can use it in the template. So instead of showing the slug, let's show locationame. And of course it's undefined initially because we have to wait for that data on the server side.
But let's make sure we actually get the data. And we do. So look at that. So if I head to the San Francisco page, we see that New York City, Dallas, Tokyo, Disney World, and this is actually pulling that data from the server. Fantastic. So now let's actually display a loading spinner if we're we're waiting for that. So this also includes the status and if the status is pending we'll show a loading spinner. So let's have this div here only show this if status is equal to pending and then we'll have a div. So we'll have a class of loading and so now if the status is pending it'll display that otherwise we'll display the location info. So we'll say if location has a value then we'll render it out. So that looks good.
Now I want to see that loading spinner just so we can style it correctly. So let's add a fake delay in our API. Show right about here. Let's wait a promise. Let's wait for two seconds then actually grab the data. So now if I click around it takes a second for the data to load. But we forgot one thing. We we want to use that lazy attribute just just like we did with location. So that way it it navigates to the page and then shows the loading spinner. So we'll head back to slug page and we need to pass in that lazy option. So lazy is true. And now as I navigate around, we see that loading spinner. And then the location information pops up. Awesome. So let's increase the size of the name. Let's make it a text large. And we only want to display this if the locations exists and the status is not pending. So say and status is not pending. So that looks good. But let's handle the not found case. So if they try to go to a location that is not found, what happens? We don't show anything. So let's also get
access to the error and if it exists we will display it. So here we'll say if the error has a value and we want to display error status message and let's give this a uh text of error and that's what we should see location not found but also we don't want to display this if the status is pending. So we'll add that here as well. So if status is not pending and there is an error, display an error and instead of text error, we should show an alert. So let's just give this a class of alert. Alert error and then we'll remove that text error. Yeah.
So that's what I want to see. Sweet. But if we go to a location that is found, we do see the data there. Cool. I think I'll increase the font size just a little bit here. Let's do a text of Excel. Yeah, that looks good to me. And then let's also display the description because we do have it. So right below that we'll have a paragraph tag and then we'll render out location.escription. I do want the the description to be just a little less pronounced. So let's give this just a class of text small. Yeah, that's much better. Okay, let's head back to our checklist. We are showing a loading indicator. We're showing the name in the description. We have the location marker, but we do want to zoom in on that location when we go to that page.
Uh empty state is shown when no logs exist. We'll handle that next. And then map shows location marker. So essentially what we want to do is when someone goes to a specific location page, we want to zoom into that point on the map and then hide all of the other markers because we'll only show markers that are associated with that specific location. Right? So we go to this page, zooms in on San Francisco, all the other points hide, but then all of the times we visited San Francisco will pop up and we'll see those markers here. Now, right now, we don't have the ability to add those location logs yet, the the times that we visited this location. But what we can do is just set the map points to only be this location. And that will automatically zoom in on that spot because it'll be the only pin on the map. So, let's add an effect here. And when the location changes, so if location has a value, then we'll set the points in the map store. So let's grab the map store and then right here we can
say map store map points is just an array of one single map point that is this location like so. And uh just like that you can see it zooms way in. And let's actually remove that delay in our API because that looks good. But now I can I can hop around the map. Right? If I click on Denver it now zooms out and then zooms back into Denver. Awesome. I think one thing I want to do is set a max zoom on whenever we're we're setting the bounds here because that's that zooms in way too far. So if we head to the map store, this is the thing that's listening for those points to change and then setting the map bounds. Uh when we do fit bounds, we can specify padding, but we can also specify a max zoom. So let's do a max zoom of 10. And now when it loads, it doesn't zoom in too far. It's a good middle ground so it's not like way zoomed in. Eventually once we have lots
of location logs associated with this location, it'll behave just like when we're on the main page because there'll be lots of points and then that zoom level will work for that set of points. But now we can click on any location it zooms in on that spot and then a bit once we have location logs those will pop up on the map too. But this is exactly the behavior that we want. Okay.
So the map shows the location marker. Now, next up, it says empty state is shown when no logs exist. So, when we go to a specific location, we need to know about all the associated logs for that location because if they don't have any logs yet for Amsterdam, we need to say a message that says add a log to get started. So, we need to update our database query so that when it returns the location, it also includes all of the related logs. And when we set up our initial database schema, we already have the structure for that. So you can see we have a location but then the location log has a foreign key ID with location ID. So that will allow us to basically query all logs with this specific location ID. So for this we need to set up some relations. So to do this we can check out the drizzle docs and they show us how to set up these relations. So the first relation we want to set up is one location can have many location logs. So that's a one to many relationship. So to
location logs relation / query
set this up for a mini relationship, we can use this example and we'll call this the location relations. Import that in from Gizzel OM. And we're setting up the relations on this location table. And we are saying that location logs is a mini relationship to the location log table.
So we'll import that that table schema. So this sets up the relationship on this side that says one location can have many location logs. Now we need to set up the relationship on the other side as well. So if we head to the location log table, the relationship here is that one location log has one location and it is related via that location ID. So we can copy this example and then set it up accordingly. So we'll call this the location log relations. Import relations. We're setting up the relations for the location log table and we are saying that a location log can have a single location. We pass in the location table and then we add our references. So the fields we're referencing is location log location ID and that references the location ID column. So this sets up the relationship on this side. And it's important to note that these relations that we set up on both sides, this doesn't change the database schema in
any way, all this does is let Drizzle know how it can relate to these two tables because we already set up these foreign key references at the database level. But Drizzle just needs us to be explicit about how those two tables relate. So with those relations set up, now when we query the location table, we can include all of the location logs automatically. So let's head to our query. So here and now when we query for a location I want to include all of the associated location logs. So right here we can say width and then you'll see that we have type completion for location logs. So the reason we're getting that type completion is specifically because of that relation that we set up here and this is the name that we gave it. So you could call this whatever you wanted but this is what the property will be called when we get that data back. So here we'll say location logs true and this will automatically query for the location that has this
slug and user ID and also get all of the associated location logs. Now we don't have any in our database right now but this will actually return location logs with an empty array and we can use that to let the user know hey you don't have any location logs. So now that we're doing that let's test it out. If we head to API/loations/Amsterdam, you can see that it's returning that empty array. But later on, once we add logs, those will actually show up there. So on our front end, we can take this into account. If we head to the location slug page, we want to display a message down here below the description if they don't have any location logs. So let's add a paragraph tag. Give this a class of text large. And we'll just say add a location log to get started. And we only want to display this if location dot location logs.length is empty. So if there are no
logs in there, we're going to say add a location to get started. Just like that. And then if that does have location logs, we'll list them out as cards with like their visit date and all that good stuff. So uh let's add a little bit of spacing here. So let's just give this a margin top of four. So that looks good. If we look at our checklist, empty state is shown when no logs exist. And then we need a button that says click here to add a log. So right below this, we'll add a button. And this will say add location log. And we can add an icon.
Let's check out icons. I think the map pin plus is what we want. So we'll set the name and the size. See what we got. So that looks good. We actually just want it to be on the next line though. So let's actually just create a parent container for all of this stuff. And then we'll move the VF and the margin top to the parent element like so. And then we'll move this button below that.
And then we'll add a little bit of margin top to that button. So that looks good. Uh now that I think about it, I kind of want that text to be small as well. So not text XL. Let's do text SM. And then let's also set this to itallic. Yeah, I like this. So add a location log to get started. They click here and then that'll take them to the add location log page. Cool. So we have a button click here to add log and we're showing that icon. So we can click on the card, we can click on the sidebar. Lastly, we also want to be able to click on a marker and also take us to that location page. Now this is going to be a little bit trickier and we're going to have to do some restructuring. So if we take a look at the map component, this is where we're rendering out the marker for the individual points. So we're bringing in point.name point.escription. Now I want to add also a two property. So that way we can detect if there's a two property, then we'll add a link on the point and then we can also add like a label for that specific button. So if we head to our types, this is where we define the map point. So I'm going to add the two property here and then like I said,
view location by map marker
we're going to have to do some restructuring and and I'll show you why in just a second. So we'll have our two. This will be a route location raw and then let's also have a two label. So this is what we will display on that button that shows up on the marker. So now let's head to the location store which is where we actually create these map points right because when we get the data back from the API we then iterate over it create the sidebar items but also create these map points now we've got two problems first off the sidebar store sidebar items let's look at its type it is expecting a location to be a map point and we just added those two properties there now before we added those properties the location that came from our database just overlapped with this type because it had an ID name description and a lat and a long but now it has these extra property properties.
So we're going to have to construct a new object. So back in the location store, this location here needs to be of that type map point. So I will create a reusable function that's called create point from location that will give us back that specific map point. So this takes in a location and then this is going to return a map point. So we'll bring that type in. And now we can specify all the properties. So I should be able to spread all of the location and then I need to add the two and the two label property. So two is just going to be this. And our two label will be just view. So I want to view the specific location. That's what it's going to say inside the button that then takes us here. Now we need the type for location. So we can handle that in our schema. So if we head to DB and then schema and then location, I want to type that represents what I get back after selecting from the location table. Now Disil actually provides a built-in utility to do this. So let's export a
type called select location and we can use type of tablet infer select. So this comes from drizzle. So now we have a type that represents actually querying and selecting from this database. So let's use that back over here. location is of type select location. So we'll import that in. And now this takes in a location, returns a map point. So now I want to use this function to actually create the list of map points. And there's a lot of different ways to go about this. I think to be efficient, I'm going to iterate over data.value once and create both the sidebar item and the list of map points. So let's say here we have our map points. This will start off as an empty array that is of type map point array. And then we also need our list of sidebar items. So we'll say our sidebar items starts off as empty. And this will be a list of sidebar item like so. Now we can just iterate over
data.value and push both the sidebar item and the map point into those respective arrays. We're going to grab each location. We'll then create our map point. So map point is going to be create map point from location. We pass in that. That gives us back our map point. And then our sidebar item is just this logic here. So we'll pull that out and we'll say sidebar items.push. We want to push that in. But in this case, the location will be this map point that we just created like so. And then after that, we can push that map point into the map points array. So we'll say map points.push map point. Now we have these two arrays. We'll just use those directly here. So sidebar items will just be sidebar items and map points will just be map points. Okay. So, like I said, there's a lot of ways to go about this. I like this because it's a single loop that creates both of the things that we need and then just assigns them directly here. Now, I'm thinking about this and actually our sidebar item instead of calling this property location, I think we should call it map point because in the future we are going to have other sidebar items
that are related to a map point, but they are not a location. They'll be a location log. So, if we actually head to this type for sidebar item, which is in our sidebar store, I'm going to rename this to map point. And then over here we can just pass in map point directly. Now that's going to break some stuff, but we'll go through and fix all of it. Now the other thing that this breaks is before we were setting our map points directly to that list of locations and the sidebar items had that location prop which is which was exactly that location and then our cards iterated over the location. So they were exactly that location too. But now our map points are no longer just the location itself. It's a brand new object, right? We created this map point which isn't the location.
It's kind of a copy of it with some extra properties. So every spot where we had that logic that said if the map store selected item is this item then that's the one that's highlighted. We're going to have to update that logic to actually check the latitude longitude and the ID. We can't just do a direct equals comparison. And so this is what I'm talking about, right? We have in the dashboard for all of those cards. We're checking to see is the selected point this exact location. and then also in the sidebar and then on the map itself.
So for each of these spots instead of doing a direct triple equals or or not equals comparison, we'll just write a function that compares latitude, longitude, and ID. So I'm actually going to put this in utils and I think I'm going to pull out this function in there as well. These are all going to be functions related to our map points. So let's create a new file here called map points. We'll then pull this out into those utils and then also export it.
We'll need to bring in these types here. And then our autoimp imports are working for utils. So this function actually is directly available here. Now the other util I want is given an item that has an ID, a latitude and a longitude, tell me is it equal to the selected point. So I'm going to export a function that says is point selected. This will take in that specific item. We'll specify the type in a second. And it's also going to take in the selected point which is of type map point. And then the type here is an item that just has an ID, a latitude, and a longitude. And the way that I'll create that is just by using the pick utility function from TypeScript. So I want to pick from the map point type, but I only want the properties ID, latitude, and longitude.
So this now gives me back a type that only has those three properties. And what's nice about this is I'll be able to pass in a location object because a location object has an ID and a latitude and a longitude. And it has other properties, too, but it at least has those three. So I'll be able to pass that in directly here. And then we can compare it to the selected point. So in here we'll say if item do ID is equal to selected point do ID and item.lat is equal to selected point.lat and item.long is equal to selected point.l long then this particular point which has an ID latitude and longitude is the selected point. Let's just do a little bit of formatting here. Now we can use this function. So I searched the whole codebase for map store.se selected point equals and so we want to find every spot where we're doing a triple equals. So if we head to the dashboard, this is one of the spots we're doing it. So right now we're saying is the selected point in the map store equal to this specific location. Instead we'll use our handydandy utility function is point
selected. We'll pass in the location and we'll pass in the map store selected point. Now if you remember we actually renamed the location prop to be uh map point. So we'll make sure to use that. But this is possibly undefined. So we're going to update our utility function to accept undefined and null for both of these and then handle it accordingly. So item is this or null or undefined and then the selected point is a map point or null or undefined. And if either of these is undefined, we just return false. So if the item itself is undefined, return false. Or if the selected point is undefined, also return false. So that helps with that. And then right here we do need to say mapap point instead. Okay, so this one looks good.
Now another spot that we'll need to update this is on the dashboard itself. So here whenever we're setting the selected point, we can no longer just set it to the location itself. We actually have to use that utility function which is create point from location. So right here I will pull that in. I'll say create map point from location. Pass in the location. And so when you mouse over the cards now it's going to use that location to construct the selected point. And then we can also use our is point selected item here. So here we will say is point selected.
We'll pass in the location and the map store selected point. And this should be fine because that's why we did that pick type because a location technically does have an ID, a latitude and a longitude. So it just picks those properties off. We don't have to do anything special. And then we can use this exact same function right below. So we will say if this is not selected then we will use that specific point. Now, lastly, on the map itself, anytime we're using triple equals, we need to use our comparison function because that point might not be the exact same thing. It just has the same ID, latitude, and longitude. So, right here, we'll also have to say is point selected. Pass in the point, pass in the selected point. That should be good to go. And then similarly right here when we're setting the icon color.
So, is the point selected? If so, set it to text accent. Okay. After this refactor, we should be good. Let's run a type check. So if we do PNPM type check, we'll check to see did we miss any spots? Did we forget anything? And then we'll go fix those. So there's a couple of spots. First up in dashboard/ad, we are setting the selected point. So let's take a look at that page. Now for the point, this is saying we're missing two and two label. I thought we made those properties optional. Let's just double check. So if we head back to our types, we didn't. So these need to be optional because it's possible you might not pass them in. So two and two label are completely optional. So that goes away.
Let's see if there's any last errors we need to fix. Okay, so at least the type errors are gone. Now, let's just confirm the features still work. Uh because the end goal is to add that view button on the map. But let's just make sure when we hover over the cards or over the sidebar, they still select. Yeah, so that still selects. That's what I want to see. When I hover these, they still select. And then when I hover these, they still select. And there are no errors in the dev tools. Okay. So, we've reached feature par. But now because we've attached that two and two label prop, we should be able to use it directly on the map here to show it inside of this card. So if we head to the map component down here on the marker is where we'll add the button. So we'll add a div. This is going to have the button inside of it. So let's make it a flexbox and we'll do items end and then we'll add a next link. And we only want to show this next link if point.2 is a thing. If point two is a thing, then we'll actually bind the two prop to be point.2. And then inside of there, we'll add the label. So we'll add
point.2 label. And then I'm going to make this a button. So let's give it a class of button. Let's do a small button. And let's do an outline like so. So now on the map, if a point has a twop, we're going to render it out as a button. And because we set up that twop in our utility function, it should take us to that page. There it is. We can click it and it takes us to the page.
Sweet. However, it wasn't on the the lefth hand side. So I think I need to use justify end instead of items end. Yeah, that's what I want to see. So I click it. That has a nice button. I can click that to go there. Let's also add some margin top to this container. So let's do a margin top of four. That pushes it down nicely. I can click it. It goes to that specific spot. Nice. And you'll notice whenever we get to this page, it's not showing that button there because we're not attaching a two and a two label prop whenever we set the map points here. Right? If we head to the individual location page here, we're just setting the location that we got back from the database. We're not attaching a two and a two label prop.
So, it just shows it on the map. Now, that was quite the refactor, but now we can go to a place by clicking the card. We can go to a place by clicking in the sidebar. And then also, if we're back on the locations page, I can click any marker on the map and then go directly there as well. So, this is the desired behavior. All right, let's commit it, push it, and move on to the next thing.
location specific sidebar links
All right, next up, as a traveler, I want to see location specific links in the sidebar. So, essentially, this changes up what the user is seeing once they reach the specific location page because if we head back to all locations, this makes sense to display all these here and also the link to add a location. But if I'm specifically on Denver, I don't want to see this list of locations anymore. And I don't even want to see the link to add a location. I just want to see a link to edit this specific location and then eventually a link to add a location log for this location. So, we want to have like a back button that takes us back to the locations page. Once we're on a location page, we want a link to that add location log. We want to link to edit it. All that's going to appear here. So, this sidebar is going to be specific to the page that we're on. So, the first item in our list is sidebar displays a link back to the locations page. And sidebar displays a link to this specific location. So, let's check out a branch.
This for me is ticket 75. For you, it's going to be much lower. Great. So, I'm on a new branch now. And let's take a look at our sidebar to see how things are currently set up. So if we're on the main dashboard page, this is where we display the sidebar. And right now, this section here, which is displaying the link to the map and the link to add location, this is static, right? This is always there. Essentially, we want this to be changeable by other pages in our app. And then down below, eventually these sidebar items will be the specific location logs, but for now, we're just not going to display anything because we don't have any location logs. So this spot right here, I want to be dynamic.
So just like I have a spot in my store called sidebar items, I'm going to create a new spot in the store called sidebar top items. So we head to the sidebar, we'll create another ref. We'll call this sidebar top items. Then we'll expose it. And now let's pull in from that list on the dashboard page. So right here we essentially just want to repeat over the sidebar top items. So we'll say v4 item in sidebar store top items. For each one we pass in is sidebar open. The label is then going to be item. The icon will be item. And the href will be item.href. But we also have that two property. So we'll pass that down too.
So we'll say we have a twop. That will be item.2. But now that we're using v4 we do need a key. So, we'll pass down the item ID as the key. And this looks good. So, now I don't want to have any of those static buttons. Now, we're just pulling from the store. And if we head back to our app, it's going to look very empty, right? Because we we need a spot here. So, first, let's handle when we're on the overall locations page. So, when we're on this page, we want to set these top items here. I'm actually going to handle this at the top level on the dashboard page because we could be in some nested route, and I always want this code to run that sets these top sidebar items here. So right here in onmounted on the main dashboard page, we're just going to have all of our logic here. So we'll say if route path is equal to dashboard, then we want to set the top items. So we'll say sidebar store.top items is an array. And in this case, the first one is just going to be our locations. The href is just /dashboard. And the icon is the map. So
we'll say tabler map. And then it also needs an ID. So we're just going to give this a static ID of link dashboard. So So now when we load the page, we do have that link here that takes us to locations. That's great. We also want to add that add location link. So the ID will be link location add. The label will be add location. It's going to take us to dashboard/add. And we want the tabler plus icon. And that is this this circle plus field like so. Okay. So now I can go to add a location. I can go to locations. Great. So that's great. When we go to the main page, these links populate, but now we want to populate them when we're on a specific location page. So here we'll say else if the route name and so we have access to the route. It'll be much easier if we use the name and that's the thing that we're passing into two before. So we'll say if the route name is the path with the slug. So this should be
dashboard-lo. So if we're here, then we'll set the sidebar items accordingly. This will just say view logs, which takes us to the map. In this case, the href is going to be specific to that location. So we'll handle that in a second. But this will say add location log. And then this will also be a more unique URL that includes the slug. So we'll update that in a second. But right now, I actually want to update our our if statement above because we'll we'll be consistent and match on route.name.
So here we'll say if route.name is equal to dashboard, then we want to show these. Otherwise, we want to show these links here. So, let's see if that works out. Great. So, we're on this page. It says view logs, add location log. Let's add a link that says go back to the locations. So, I'm going to add that link right above this, which will look exactly like this, but just says back to locations. We'll say back to locations, heads to the dashboard, and instead of a map, I just want to display an arrow left. So, we'll head to icons. Let's look and see what arrows we have. I want just this one. arrow left is what we want. Like so. Yeah. So, this looks good. And if I click back to locations, it breaks because this actually shouldn't be in onmounted. This needs to be an effect, right? Anytime the route changes, this code needs to run. So, I'm actually going to pull all of this out into an effect. Exact same logic, but now anytime its dependencies change, which in this case are the route, it should rerun. So, yeah, I'm on the locations page. We see those two items.
I go to Denver. We now see these items, which is awesome. Now, we just need to work on getting the correct links in these two items here. So, this link right here ultimately needs to be this URL because it's going to link to itself. So, dashboard/lo/s slug. Now, in order to get access to that slug, we need what is the current location that they're on. And we don't actually have access to that in the whole app because right now we're only requesting that data whenever we are on the specific location page.
Right? So, this is where we make that fetch. So, we're going to do another refactor and essentially just create a new store. So, that way I could get access to the current location regardless of what page I'm on. So, we already have a store that manages all of the locations. I'm actually going to pull this logic in here so we can both manage individual locations and all of the locations. So, let's grab this codes here. And then in our locations store, we want to do this as well. However, we do need access to the current slug. So, inside of our store, we are going to get access to the current route. so we can keep things updated accordingly. So let's grab the route. This will be use route. And then this URL needs to be dynamic based on if there is a slug. So I'm actually going to create a computed property that we can pass in here. And that way that URL will will always update. So let's call this the location URL with slug. And this is going to be a computed property that essentially does this but it takes into account the current route. We'll do this. But this needs to be route.slug like so. And this should give
refactor current location into store
us back a string. And then we want to pass that string here instead. Now we'll remove await because we can't do that at the top level. And then the other thing I want to do is I actually don't want to call this immediately when the app loads, right? I only want to call it if route.params.slug actually has a value. So initially I'm going to set immediate to false. So that way this doesn't fire when the app first loads up. But whenever we know that we have access to the slug in the URL, then we will fire this off with our refresh method. So let's go ahead and do some renaming so things don't conflict. So first of all, let's rename this data property to be locations because that's what it is.
It's the list of locations. And then we'll rename these so they don't interfere as well. So this will be the locations status. And then we'll rename this to refresh locations like so. So that looks good. So now instead of exposing these as just status and refresh, we actually do want to expose them as locations, status, and refresh locations because that way they're specific to the list of locations and then we'll have other variables that are specific to the current location. So all the spots that are referencing these need to be updated and the top spot is in the dashboard, right? This is where we call refresh to relist those locations, but this needs to say refresh locations and then on the individual location page, we should say refresh locations. And then now status is actually the locations status and then we'll just rename that to status inside of this component. So that's looking good. Now let's keep working on this. So we get back the location. I'm going to call this the current location. And then we'll rename these to be current
location status and current location error will be error. And then we also will need to expose refresh so we can actually call it from the component. So we'll expose refresh. This will be fresh current location. And that looks good. Let's do some formatting because these long lines are getting out of hand.
Okay. Now, I do want to expose all of these from the store like so. And now we should be able to call them from within our location slug page. So, if we head back to the location slug page, now we want to get access to the location store. So, the location store is use location store. And then when this component gets mounted, we do want to call location store refresh current location, right?
Because if this component mounts, we know that there's a slug in the URL. So that refresh should work, which includes the current slug. And then similarly, once that location has a value, we want to set the map points. So we need to pull off all of those other properties from the location store. So here we will use that store to refs. So we'll say store to refs. We'll pass in the location store and then we can get access to all the things we need like the location and the status and the error. So we'll say the current location, pull that off as location. The current location error, pull that off as error. And the current location status, pull that off as status. Let's do some formatting. Shouldn't need the route in here anymore. Now, we do have a type error here because our types are not actually flowing through for the current location. And that's because we're using a computed property in the store. So, if we head back to the store right here, it has no ideas what what this could be because this string could be anything.
We know that this will only ever return a location. So, use fetch actually is a generic. We can pass in a type here. And in this case, we'll pass in the select location type that we created a little bit ago. And this now lets it know that, hey, you're going to be getting back a single location. Now, we currently have a type error. You might have seen the the red here. Uh right now, we're expecting the current location to have a list of location logs. So, we do need to update that type. So, if we head to our database, head to the location schema, I actually want to create a new type that is select location with logs. And that way, I can use it anywhere where where we're doing that query that includes all of the logs along with the location. So, I'm going to export another type that is called select location with logs. It's going to be a composite type that includes select location and location logs, which is an array. Now, to get the location logs type, we'll need to do an infer select. So if we head to the location log table. Let's export this type. Select location log. It is of type location log in first select. So that
gives us the type of a location log. And now we can use that type right here. So location logs is of type select location log that comes from that table. And it's an array of those. So now we can use this type to represent a location that has that list of logs. And instead if we head back to our store now we'll use that type here. We'll import it in and then get rid of that unused import. And that should fix the type error over on our location page because we now have access to those location logs. Okay, let's double check we don't have any errors. Let's double check that everything is working correctly. If we head to a location page, that works just fine. And then if we head back to locations, you can see we're actually getting this request for location/ undefined. And this is because our fetch is dependent on the route. And when we go back to this page, slug is completely undefined. So we actually don't want our use fetch to always refetch if the route changes completely. So what we'll do is also pass in watch as false. So that way
this location fetching is going to be completely manual. Essentially the only time this will have data is if we actually call refresh current location. So with that I head to the main page. We should be good. No errors. Doesn't make any requests. If I head to Denver it has the data for Denver. Can list it out here. If I head back to locations, we don't see that request to undefined. And then if I click a different spot, that should run refresh current location because we have it in unmounted. And so this component is mounted again. And then we have access to that current location. Awesome. So this is looking good. But the main reason we did this is I want to get access to the current location so I can change these URLs dynamically. So if we head back to the dashboard where we're setting those sidebar items, we can do that right here. So right here, I need this to be dashboard/loations/lug. So I'm actually going to pass in a two prop. And this will be an object where the name of the place we want to go to is dashboard-loation dash slug. And then
location specific sidebar continued
the params will have the current location slug. So this will be current location slug. Now we need to get access to current location inside of here. So we will use our store to refs method. Pass in the location store. This will give us access to the current location and then the slug here is just going to be location valueue because it is a ref.
slug. But it is possible that current location is null. So this is fine because this reruns anytime it's dependencies change and basically it'll it'll be unknown for like a split second and then the actual link will pop in. The other thing we could do is now that we have access to the current location, we can put that in the label. So instead of saying view logs, we'll just put the location name. So right here, I'll say if current location.value has is a thing, then let's use currentloation.name in the label.
Otherwise, it'll just say view logs and this is currentlocation.value.name. So just like that, now we can see there's a link to Denver and it is takes us to the page that we're on. So that's great. Now we can use this to construct a URL for ad location log. So, we will do a very similar thing down here, but instead of hard- coding it to dashboard/ad, it will go to dashboard location slug-add, which doesn't exist yet, but it will exist soon. And then that would be the slug to take us there. And it doesn't exist. So, actually, uh, Nux throws an error because of this. So, let's just go ahead and create a blank page. So, this would be in location slug ad. So, we need a new folder here that is slug. And then inside of there, we need a new file that's add.view. Let's create a basic template here. Give it a title, the location log ad page like so. And now that should resolve. And if I click this, then it takes us there, which right now doesn't display anything because we're going to have a further nested route that we'll set up later.
But this is great because I'm on the locations page. These links are specific to that. If I go to a specific location, these are specific to that and I can go back to locations. That's exactly the behavior that we want. We check out our story. We have a link back to locations. We link to this specific location. Let's also add a link to edit this location. So, we'll be working on that next. The ability to change the the name of Denver or the description. So, we need an edit page. And let's just add that link right above the add location log. So, we'll call this the link location edit. The label will just be static. It'll just say edit location. And then we want to go to dashboard location slug-ashedit and then pass in that slug.
So we'll create one more dummy page that's just called edit. That will take us there. And then the icon I think should be like an edit icon, a little pencil icon. Now if we search for map pin, I know there are some ones that look like this. Yes. Is there one with a little edit icon on it? Could use the settings one cuz that's kind of like editing this specific location. I think that is what we'll do. We'll use this one here. So, that will look like that.
And now we have the ability to go to the map, go to the edit page, go to the ad page, and we can also go back. Um, like I said, all of these we're going to set up in some future stories, but at least those buttons exist there for now. And then lastly, the location list in the sidebar is no longer displayed. So, essentially, the only spot where we want to list out these locations is if we're on the main dashboard here, right?
Dashboard/ad or whatever else, but just dashboard. If we're on a specific location page, we don't want to show all of the other locations because eventually we're going to show the specific logs for this location in this area. So, let's handle that. Right now, in the locations store is where we are actually updating these sidebar items right here. And we really only want to do this if the current path is slashboard or slashboard ad. So, let's create just a little static list of all the paths that should display this list.
So let's call this list locations in sidebar. And the specific route names that we care about are the dashboard page and the dashboard- add page. Those are the only spots where we want to display those locations in the sidebar. So we'll take that into account here. And I'm actually going to create this as a set. So that way we can easily just reach in and say does it has this this current route name. Okay. So now that we have that down here, we'll say only set this stuff if the list locations inside bar has the current route name. If the current route doesn't exist, we'll just pass in nothing. And this also we should string to get back a string value. Okay, so now when we're on this page, it shouldn't list those locations. But if we head back to the locations page, it does list those locations. And then if we head to an individual locations page, they're still displayed because we'll now have logic that says when you're on a specific location page, set these to be the location logs. So let's do some initial work there. We are kind of
getting ahead of ourselves cuz we do have a story that says see my location logs in the sidebar, but I do want to at least handle that right now while we're thinking about it. Now to clear this sidebar, it'll be very similar to how we're setting the sidebar, but we're just going to use the location logs. So here in the location store we're listening if locations changes and if it does we're setting the map points and the sidebar items. So below this we can say otherwise if the current location has a value and we're on a page where we want to display the the current location items then we will set the sidebar items. And for now I'm just going to set them to an empty array. We'll actually update them in a future story. And for now, I'm also just going to set the sidebar points to be this specific location. And that will actually allow us to remove that logic inside of the location page with that slug. Uh, but we now need another list of pages that should list out the location logs. So, we'll say uh list current location in
sidebar. So, for this, we want to show the dashboard-loss slug page. We also want to show dashboard-loation-slug-edit and then also dashboard location slug add. Those are the the three pages that we want to display the list of location logs. So similar logic here if this has the route.name to string or just default to nothing because otherwise we don't want to display it like so. And like I mentioned we can get rid of that logic in our location slug page because we're now handling it in the store. So here on the location slug page, we no longer need to set the map points here because that gets set in the store whenever that value changes. So we can remove that. We don't need access to the map store anymore. Moment of truth. If I refresh and load the Denver page, it's a we don't see that list there. If I go back to the locations, we do see that list.
If I head to a separate location, we don't see that list. This is what we want. And like I said, eventually we're going to list out all the individual location logs for the specific location. In this case, New York City. But this is it. We have a dynamic dashboard depending on where the user is inside of our app. Okay, so that looks great. Let's add it, commit it, push it, move on to the next thing. Now, this next story, I go down a lot of rabbit holes and I touch things in a lot of different places and I'm also moving kind of fast.
update location details form
So, I apologize for that. But I will say if you just want to see the code that I update in this specific section of the video, check out the commit logs. There's one that is called update location details. It has ID 2B 0D934. But if you go directly to this commit, you can see every single file that got added, also what I changed and all of the other things that got updated in this specific story because we did a lot of refactoring. I was bouncing between files. I realize in retrospect it might be hard to follow, but like I said, if you want to see the code that was changed, check out this commit here and that should help you out. All right, next up, as a traveler, I want to update location details. So this is essentially going to be an edit page for an existing location. So let's check out a branch and this is going to be number 31. So for this all location fields are editable. Current values are pre-populated. Validation prevents invalid updates. Changes are preserved if the submission fails. Loading spinner shows during update. Confirmation dialogue appears for unsaved changes.
And a save button shows with a check icon. So all of this is very similar to the page we have for adding a new location. Right? If I click add location, this has a lot of that. Essentially, we just want this form, but the ability to edit, right? I want to pre-populate it with Denver and the description and the coordinates, and then the user should be able to update it. So, because of that, I'm actually going to extract the form part of this out so it can be reused on multiple pages. So, let's go and do that, and we'll make sure our ad page works as expected, and then we can reuse that component for our edit page. So, if we head to dashboard add, we can take a look at what we want to extract out here. Now, we're definitely going to extract out just the form piece and then we're also going to pull out any state or methods that the form needs from the top of the component here. So, let's head to the components folder. We'll create a new component called location form. Give it a template and then let's extract out the form piece. So, basically all of this is now going to
live in its own component like so. Now we can go grab all of that state. So we're definitely going to want this use form. Pull that out. We'll add our script. It's going to go in here. Format number is also something we're using in the component. So we'll pull that out. And now that I'm looking at the codes, we can see that we're listening for like search results selected and we're also listening for like when that added point moves. So, I actually think we're going to move this place search into the form as well because that's going to be used both when we're editing or adding because later if we want to edit that location, we would still want the same behavior of dragging around or maybe searching for a new spot. So, I'm actually going to pull this into the location form as well. So, that will live here and then we can pull out the state. So, we need this effect and we also need search result selected and that will live in here. And now we're going to need that map store. So, we'll pull that out. That's going to live in here as well. And then the logic for setting that point when this form loads onto the page that's going to live inside of the form as well. And so
essentially our ad page really the only logic it's going to have is calling the API to create the location. And then whenever we reuse this component that edit component is going to call the API to update the location. But all of the other logic is going to live here in the form. So we can pull out all of these imports as well. And then this function will live inside of this component. But we're going to need to pass it down as a prop. So we'll have that here. We'll just call it onsubmit. And then handle submit is going to get called inside of this component with the prop that gets passed in. So we'll do this. And then we'll pull the router out as well. So that lives there. And then we'll also pull out on before route leave. You can call that from any component. It'll make sense to put here because this is the logic that prevents the user from leaving the page and and losing all of their unsaved changes. So we'll need that for both when we're adding and editing. Okay. So this is looking good so far. Let's figure out what our props need to be that we pass down. So right here we'll have our props. This will be define props and the first one we need
is onsubmit. So we'll pass in the type onsubmit should be a function that takes in an insertable location and then just returns a promise. So this will accept the location. We'll call it the insert location that comes from our types. And this we'll just say returns a promise of anything. And now that we have the prop, we can pass it in here. So handle submit will be props onsubmit. So that looks good. And then this form needs to know whether or not some processing is happening in the background. So we do need to pass down loading as well. So here it will say loading is a boolean.
So that gives us access to it. And now the form has pretty much everything it needs except for knowing if it's been submitted or not. So we'll also include that as a prop. So submitted will also be a boolean. And then we can pass that down. And in this case it's going to be props.submitted. not submitted, which will be a boolean. Okay, no more type errors in here. The only thing is being able to set the errors on the form itself. We'll figure out how to do that next. But now, let's get an instance of the component inside of our ad page. So, if we head back over here now, right here is where we want our location form.
And then we can pass down those props. So, we'll pass down submitted, which will be our submitted state variable. We'll pass down loading. And I don't know if we've done this in this tutorial yet, but because the prop has the same name as one of the state variables that we're passing down, we can just use this shorthand here. And then onsubmit, we can also pass down as well. So pass down on sububmit. But the types don't overlap because right now we just have it as any. So this should be our insert location type. So the only thing missing is the ability to actually set the errors on the form. So here's what I'm going to do. So I'm actually going to wrap this up into a state variable so it can be passed directly down. So I'm just going to call this the submit errors.
This will start off as an empty object, but it will be a generic object. So we'll call it a record string string like this. And then if we get those errors back from the API, we'll set it here like so. And then we'll pass those errors down. So here we can just say the submit errors are those errors that we set. And just like we're resetting that error message, we'll reset the submit errors whenever they submit the form as well. So now that we're passing it down, we need to take into account submit errors in the form itself. So submit errors will be a record string string.
And then I essentially just want to have a watch on this. So if these ever change, we can call set errors with them. So I will set that up as an effect right here. So we'll have an effect and we'll call set errors with our submit errors, which is props.submit errors. Okay, this looks good to me. Let's let's see if it works. So, essentially, we extracted all of that form logic out of this component. We're handling everything with props and then all of the logic is handled inside the location form. So, let's start from scratch.
Let's head back to the travel log. So, let's head to the add location page. Don't see any errors in the console, so that's good. Let's give it a try. Let's try adding Las Vegas. So, I'll click there. The marker moving still works. That's great. It's updating the location here. Let's see if we can also search for a place. Yep, it shows as loading.
We get back our results. Let's set it. Okay, so that's working too. Now, moment of truth. When we submit, will this actually get added? So, we'll give it a description and then hope for the best. And that looked like it added it. We'll look at the console. Yeah, no, no warnings or errors here. And it did get added to our list. And we can click on it, load it in. Okay, so the form still works, but now it's its own component.
So now we can reuse it on the edit page. So if I head to an existing location and we go to edit location, I want to use that form there. Now this will be a case of another nested route because by default I'm on location/slug. But then if I go into location/slug/edit, that should load the edit page on the left here. But this needs to be a nested route inside of the location/slug page. So if we head to location slug, the spot where we want to render out this page is going to be here. Essentially, I only want to show the this text that has the location name. I only want to show this div if we're on the main location/slug page. If not, I want to show the nested route.
So, I think I'm actually going to move this below the error here because this error should still pop up if they go to like a location that's not found. But I want to conditionally render this section only if I'm on the location slug page directly. So, in here, we should get access to the current route. So we will use use route like so and then we can take it into account in our if statement. So um if the route name is equal to dashboard location slug. So if we're exactly on this page then we will render out that information about the specific location. If we're not then we need to render out a next page. So, I'm just going to have a div if here. And then we'll just throw in the next page.
And we'll throw our v if in here just to prevent any v else rendering issues. And we will only render this nux page if we are not on the location slug page. And the only time that would be is if we're on slug/add or slug/edit because this is a a nested route. So, now that we have this, head back to the app. We're on the location ad page. And there is a bug here where these aren't populating.
We'll we'll fix that in a second. But if we head to Denver, I can go to add location log. That's the ad page. And then I can go to edit, which is the edit page. But I don't know if we updated that message. Yeah, we need to update it. This is the edit page. Yeah. So, we have the edit page. We have the ad page.
And then we have the homepage, which is this location itself. So, that looks good. We've got our nested routing. This is our second nested route. So, we have a nested route that renders this stuff out and now a further nested route that's rendering out our location specific stuff. But let's fix this bug where if I'm on like a page like this, then I refresh the sidebar does not populate. So, if we head back to our top level dashboard right now, we're just doing a a triple equals. So, if we're on the dashboard location slug page, add these sidebar top items. But we also want to do this if we're on dashboard location slug add or dashboard location slug edit. So, if you remember in our location store, we're doing a very similar thing, right? These are all the pages we want to render that sidebar out on. I'm actually going to pull this out in as a constant so that way I can use it in both spots. So, I'm going to pull both of these out. We'll head to lib constants, find them here, and export.
Let's give them a more useful name now that they're in a constant spot. So, let's call this the location pages, and then this will be the current location pages. Okay. Now let's use those in the store first. So this will be location pages. We'll import that in. And then this will be the current location pages.
But now we can reuse both of those variables on our main dashboard page. So we head out to here. If the route is within that set for current location pages, then we want to set these sidebar items. So right here we'll say if current location pages we'll import that in from constants has this route name then we add these and then we'll do the same thing for this one except we'll check for all the the dashboard pages.
Um but in this case we do need to to string this like so and then we'll do the exact same thing here but we'll check for the location pages like that. All right this should handle it. So if I go directly to the edit page this gets populated. If I go directly to the ad page, this gets populated. And then we also need to make sure if we go to the add location page and refresh, this also gets populated. So our sidebar is in a good working state, especially if we're inside of these these nested routes. So now let's work on this edit location page. So if I click on this, I want to render this on the left half just like I did for the add page. So let's do that.
If we take a look at the dashboard down here, we're doing that conditional rendering where if we're on dashboard, then we should be flex column. We want to do the same thing. If we're on dashboard/lug/ad or dashboard/slug/edit. So, let's create another constant that has all of those paths inside of it. So, we're going to call these the edit pages. Essentially, these are pages we want to appear on the left with full height because they're going to have a form in them. So we want that for the dashboard location slugedit dashboard location slug add and then dashboard slash add. So if it's any one of these three pages render it on the left half and now we can use this here.
So instead of saying route.path equals we will say if edit pages and then we'll make sure that we import this from constants if this has the current route name like so. And I do want to reformat this just so it's a bit easier to read. And I want to do this if it does not have that specific route because all of those routes I want to be rendered as flex row. So I should invert this like so. So if we're not on one of these pages, use flex column. So it'll be the page on top of the map. But if we are on one of these pages, it'll be two columns. Let's save that. Refresh. Okay.
So main page looks good. If I go to add location, that looks good. If I go back to locations, click on Denver, and then go to edit Denver. Look at that. It loads on the lefth hand side. Also, eventually we're going to add a location log. That's going to render out here as well. This is what we want. So, now on the edit page, we're going to reuse that form that we used on the add location page. So, first up, let's just get it populating on the location edit page.
So, right inside of here, I need that location form. We need to pass down all of the same props. So let's kind of copy what we have here. Pass it down in a similar way. Define all of our state and variables in a similar way. So we'll just paste that in. Now the main difference for this is we're actually going to be calling a put on locations to update this individual location. Uh but for now, let's just make sure that all of this is hooked up and working.
And then I actually sense one more refactor because really all of this logic could exist inside the form. The only thing we do is we change where we we send that data. And then we also change potentially what we navigate back to. But for now, just going to comment this out, log the values, and see what happens. Okay, so that's looking good. It renders the form out here. Now, I want this to actually prepopulate with the values for Denver, right? Because we're currently on Denver, I want this edit form to say Denver, have its description, and this movable marker should actually be on that specific point. So if we take a look at the location form that we just extracted, we're hard coding a couple of things.
Right? Right now we're just hard coding name and description as empty and we're always centering on center USA. So one more prop we need is the initial values because if the initial values exist then we're just going to pre-populate the form with those initial values. So here on the props we'll also specify initial values. This will be of type insert location. But it is optional, right?
Because in the case of adding a new location, we we aren't going to have initial values. But when we are updating a location, we have those. So here, I'll just say let's use props.initial values.name or default to the empty string. And then same thing here, let's use props.initial values description or default to the empty string. And then also do the same thing with launch and lat. So props.initial values. Like so. If we pass down initial values, the form should be prepopulated with those initial values. Now another spot where we were using center USA is when this component is mounted. We add the added point to the map. In this case, we should use our initial values to set up where that marker initially goes. So here we'll also pass in uh props.initial initial values long and props.initial values.lap. So that's looking good. Now we need to actually pass down those
initial values to this form. So if we head back to the edit page inside of here, we should get access to the current location which exists inside of the store and then pass it down to the location form. So we're going to grab the location store. So be use location store and then we should be able to pass down the initial values as location store.curren location. Now it's possible that current location is null. So let's actually update our type as well because our current logic will work in the same way. So we have that or null because this logic will still work whether or not it's null or undefined. So with that my hope is that the form is populated and the marker appears on the right spot on the map. So, it appears that the form is populating with those initial values.
fix current location SSR
And if I go to this page first and then go to the edit location page, that works just fine. But if I refresh the edit page, it actually doesn't pre-populate because the way we've written things right now, that request for the current location is actually only happening on the client side, and we want it to happen on the server side. To see this in action, you actually can look at the network tab. And if I do a full refresh of this page here and let's filter down to localhost, we can see all of the requests made to our server. We can see that the client side is actually making that request for the data associated with this current location. And we don't want that because we're using server side rendering. We want that data to be available on the server side. So we can fix that. I've done some soothing to figure out what we need to do. But essentially, if you look at the slug page itself, this is where we're refreshing that current location. And it turns out that this is happening on the client side. So in order to make this data available for all of the pages below it, we should await at the top
level. So I'm essentially going to call this inside of our main dashboard page if we are serverside rendering one of these nested pages. So if we head back to dashboard.view, we can also essentially kind of like get rid of this logic here because we can do something similar. So what we'll do at the top level inside of dashboard is say if we are headed to a location page. So this very similar logic here. Then we will await location store.refresh locations. That's the list of locations. And this await keyword is at the top level of this dashboard component. Which means the component will actually wait on the server side for that data to be available before it finally renders it out. And we can do the exact same thing if we're headed to one of the current location pages. So here we'll say if we're headed here then I would like you to await refresh the current location and this like I said is going to happen at the top level. So if we're making a serverside render of location/deenver this code will run it'll wait for the data to be available
and then finally when this page goes to render it'll already have access to that data. And because we're using use fetch inside of our store it's smart enough to not make that request again on the client side. It's going to see that it already has that data. So with that one change, let's go ahead and clear everything out. We'll head to the edit page and do a hard refresh. You can see that now on a hard refresh, this data is available because we waited for it before server side rendering this page.
So this is absolutely the behavior we want. Now you might have noticed this little dropper in the left corner here. I actually used this plugin called Nux Hydration that helped me find some hydration errors when we were fixing that issue of only requesting the data on the client instead of on the server. So, this actually let me know that this data in the sidebar wasn't becoming available until we were on the client side. And then that's how I was able to track down the fact that we need to make that data available on the server side.
And now we can uh keep moving with this edit location page form. Now, one thing I mentioned earlier is I think I actually want to pull all of this into the store so that way we're not duplicating our loading logic and submit logic. And that can just happen inside of the form. The main thing we want to change is what actually gets called whenever we click submit on the form. So if we head back to just our add location page, I am going to extract this out into the component and then restructure it so that this onsubmit function just takes in the values and doesn't have to do all of the other stuff. So if we head to the location form, we're going to pull all of this in here as well. So we have access to all of these. We'll pull in fetch error. And now right here is where we want to call onsubmit. So instead of passing the onsubmit prop into handle sububmit, we're actually just going to call handle submit just as we did before by passing this function in directly like so. And now this
update location details form continued
handles all of the logic. And instead of hard coding where we call the API, we can just use the onsubmit method that got passed as a prop. So here instead of using cesurf fetch, we can just say props.ubmit. Pass in those values and we will await it. Now I'm going to do the navigation on the other side because we can specifically decide where to navigate the user after the creation is done. But otherwise this is all we should need. And now we can get rid of a lot of these other props too. So we only need access to onsubmit in the initial values. Everything else will be handled as just state inside of this component.
So we don't need csurf fetch inside of here. Uh now we can just set it as submit errors.value and this can be submitted.value. And also because we moved the errors back into this component, we don't need a special state variable for it. We can actually just call set errors directly inside of our fetch there. So we can get rid of that effect. We no longer need submit errors.
And then down below whenever we were setting the errors, we can just pass those in directly and we don't need that anymore. Okay, so this component is handling all of that logic. Now if we head back to the ad form, things will get much simpler. So the only thing we need to pass down now is onsubmit and we can get rid of all these state variables but onsubmit will literally just do a curf fetch and then it will navigate to the page it needs to go to. That is it.
And now this submit error actually lives inside of the form. So we can even move this error message to be inside of the form. So we head back to the location form. This can appear right above the form here. Okay. Sorry for jumping around so much, but I think we're in a much better spot now. So, because this add location page is so simple, our edit locations page is actually going to be just as simple. Right now, all we need to do is pass it an onsubmit function and we basically have our edit. We'll have to implement the backend, but this is all we will need. We can get rid of everything else. And now our edit form is in a really good spot. And in this case, we'll we'll have to implement the back end, right? So right now, let's actually just log out the updated values. But we should be in a spot where we can test it out. So because we did all of that refactoring now, if I go to the edit page, let's do a hard refresh.
Let's make sure there's no errors. There's not. Now if I try to update this, let's say I just add an extra exclamation mark and click add. This calls our method with the updated values. Similarly, like if I change the location and then add it, that sends over those latest updated locations. So this is actually the data that we would want to send to our API in order to update this one specific location. Now I was actually curious about how our app would behave if the data loading for the individual location was a little bit slower. So I added in this set timeout here for requesting a single location.
fixing data loading issues
And let's test this out. So let's say we just go directly to like Houston, Texas. You can see the dashboard says that in the URL, but these sidebar items have not updated yet. So if I click on them, it actually has the last location that I clicked on. So really, we shouldn't actually have a value on here if we are currently loading the locations. The other bug here is we shouldn't display this form if we're waiting for that data from the API. So we need to take all of that into account. So first of all, if we head to our main dashboard page, this spot at the top of our component is where we're setting these sidebar items.
And one thing I thought of is the slug here actually doesn't need to be dependent on the current location. It can just be whatever the slug is in the URL, right? Because this will only ever run if they're actually on a page that has a slug. So in that case, we're actually just going to pull in route.params.slug instead of pulling it from current location. That'll prevent the sidebar from having the wrong link if we navigate to a location before the previous location finished loading. So here I just want to say route.params.slug. And then we'll do that same thing for each of these. And that'll make sure that we don't have the wrong links there. The other thing is the label here. Instead of just saying view logs, let's actually just say loading because we don't actually know what the location name is yet. So that should at least fix our sidebar. So now let's say I loaded into Denver. So all of these should have Denver, right? So I can edit Denver. I can add a log to Denver. If we go back to the locations and then quickly click click something like Disney World, now these links don't link off to Denver. they actually have the current slug, which is good. The
last thing we need to fix is this edit page, right? So, again, I'm bouncing around, but let's say we go to Dallas and then we wait for the data to load. Okay, so we have Dallas and then if we go back to locations and then click something else and go to the edit page, you can see that it's pre-populated with Dallas and then all of a sudden we're actually on Disney World. This is not what we want, right? This form should wait to render until we know that the current location is not loading. Uh the other thing I noticed is this is just displaying the previous name. So we also need to take into account whether or not the current location store is pending whenever we set this. So right here we also want to take into account that status. So let's actually bring in the current location status. And if that status is pending then we want to display loading. Or if the current location value is not defined meaning we're still waiting on it then we display loading. Otherwise, if we're not pending and the current location has a value, then we will display the current
location's name. So, we load a page, it's Disney World, that's great. Let's say we go back and we click something like New York City. It says it's loading. It's loading. It's waiting. And then finally, New York City pops in and it navigates over. And then if I click this form, it's populated. But this is the last bug here we need to fix because if I go back, click something else, and then go to the form, it has the previous location's values. So essentially we do not want to render this form if the current location is currently pending.
So if we head to the dashboard location slug edit page, let's not render this form unless we are not pending. So we can grab the current location status from the location store. So we'll say only render this if the location store current location status does not equal pending. Then we will render this form and that should stop us from showing it with the previous values. So, if we go back, we click another spot, we go to the form, now it's loading, and then it loads in with with the values of the thing that we clicked. But we did also notice one more bug, which is the width of this should probably be a fixed value if we're on one of these edit pages. So, first, let's go ahead and remove that pause from the API, so things load a little bit quicker. And then now, I want to give this area a fixed width if we're on any one of those pages. And we're pretty much already set up to do that. So if we head to the dashboard page, this route here, we want to give a fixed width if we're on one of
these edit pages. So I'll do a class binding. And in this case, I want to apply this class if we are on the edit pages. And for this, I'll just give it a width. Let's do a width of 96. It's about 384 pixels. And then we also want to make this shrink zero. So because this is inside of a flexbox, we don't want it to shrink down. we want it to take up that specific amount of space.
So, let's do a shrink of zero if we are on any of the edit pages. So, now this has that nice width there. And if we head back to, let's just say the ad location page, it's going to have that exact same width and it's not smooshed like it like it was before. And similarly, like if we go to this page, it has that nice width. So, that's what I like to see. Now, one more thing with our custom form component is we want to change the text of this button and then also the icon if we're on the edit page because it shouldn't say add anymore. It should say update. So, if we head to the location form right here, we want to say update. So, we're going to pull this in from props. So, we'll just say propsubmit label. And then we'll also pull in from props the submit icon.
update location details form continued
We'll bind that there. So then we'll also take in those two props. The submit label which is a string and then the submit icon which is also a string. And now on the location add page the submit label is add and the submit icon is tabler circle plus icon filled. And then for the edit page the submit label should be update. And then the submit icon will be an update icon. Let's see what else we have for these map icons.
Let's actually go with this map pin up because to me that signifies we are updating this one specific location. So we'll use this icon here. So now when we're on the edit page, we have this update button. But if we head back and go to the add location page, it says add. That's exactly the behavior we want. This indicates to the user what that button is actually going to do. So now let's get it so that when we click this update button, it actually calls the API and updates it in the database.
update location details api
So if we head to our API, we now want an endpoint which is going to be locations/slug.put. So if we make a put request for the location with this slug, that means we're sending values to update an existing location in the database. So let's just copy this one. We'll call it slug.put. And we will have similar logic, right? So if you're trying So first of all, you need to be authenticated to be able to update a location. Then before doing anything else, we should actually validate that the data that they sent us is valid. and we'll validate it in the same way that we validated creating a new location. So if we look at locations.post, we're going to want to do a very similar thing where we read the validated body and then if it was not a successful parse, we send back that error. So let's go ahead and import this in from our DB and then also import this in from our utils.
So right off the bat, validate that they're sending us a valid body and then if they have, we'll attempt to insert it into the database. Now, if we look back at locations.post, post. We're actually going to want to do this same thing here where we make sure that the name that they're trying to change this to doesn't already exist because we want that exact same logic. So, we're going to do the same thing here. I'm kind of sensing a refactor, but I don't exactly know how I would refactor this out. So, we're just going to have the duplicate logic for now. I will say I do like that it's technically duplicate logic, but at the same time, we're kind of deferring to our built-in functions. So, really the only duplication is the fact that we're calling functions that we ourselves define. I'm okay with this for now. So if they tried to update the name to be something that's already existing, they're going to get back that error.
And if there's no location with that existing name, then we can just update it in the database. So for this, we're going to create a query function. I'll just say update location by slug. And this is going to take in result.data. So this is going to be the values that we're going to be updating it with. We'll also take in the slug so we can query for this specific location. And then we'll also take in the user's ID to make sure that they own it. And we'll only update the one that has their ID on it. Like so. So now we need update location by slug. Going to head over to our DB and then our queries. And I'm going to throw this at the bottom here.
It's going to be very similar to this function here. So I'm just going to copy it. And we're getting the updates. We'll call this updates. And we don't want to insert. We want to call update on the location table. And then for the update method, we can use set. And in this case, we're just going to pass in our updates directly. So set it with those updates. And the main way we'll make sure we're updating the right thing is we need a wear query, right? We only want to update where it has that slug and that specific user ID. So on the end, we'll tag this with where. And we can pass in our query. In this case, it's going to be similar to one we did earlier where we have the slug and the user ID. So I'm going to copy this, throw it in there, and this is looking good to me. And now instead of created, we can call this updated. and that will be the thing that we return. So now if I make a put request to API location slug, we're going to validate the body, make sure they're sending us a valid update.
Make sure they're not trying to change the the name to something that exists in the database. And if all of that seems good, we will make those updates in the database. So we'll import this function in. Now, one last thing is when we're looking for an existing location, if we didn't change the name, this actually is going to give us back a location. So, it's not always the case that that location already exists. If this existing location does not have the exact same slug, then that means we're trying to overwrite some other one. But if we also say if the existing location was found and its slug does not equal the one that we're updating, then we're trying to create a new location with the same name. If the slugs are the same, then that means we're just trying to update an existing location with that name. And now we'll give it a try. So in our front-end codes here is where we would like to make a put request and then the endpoint that we're going to hit will have the slug in the URL. So here this will be API/loations slash the current slug and
we'll grab that slug from route.params.slug. So let's pull in the current route. So we'll say use route. That gives us access to it. And then finally, if this was successfully updated, we should navigate back to this specific location page. So here we can say the name of the route we want to go to is dashboard-loation- slug. And then we want to pass in our params where the slug is equal to route.params.slug. So if we did everything right, this will call the endpoint to make that update and then navigate back to that page and we should see those latest updates. Now, it there was a lot of refactoring to get here and a lot of bugs that we had to chase down, but I absolutely think writing it this way is worth it. Right? We basically took all of this logic that we worked hard on earlier, this location form, and made it so that we can use it in both spots, right? The the logic for the ad form is very simple. And then the logic for the edit form is also very simple.
And we can reuse it in both spots. All we have to do is specify what what should the buttons say and what endpoint should they call. So, I like this refactor, and I'm I'm happy that we did it, even though it was it got convoluted at certain points. Okay, so now let's give it a try. We do a hard refresh here. Let's try updating the description to have multiple exclamation points.
We'll click update, and we see this message. So, I think we actually need to handle whether or not the form is submitted. It's getting changed a little too early, but if I click okay, that did not update the description here. If we do a refresh, the description is updated. Okay, couple of bugs to fix. First of all, we don't want to prompt the user to say, are you sure you want to navigate away? Uh because we do in this case, the update was finished happening. So I think what we need to do is if we head to the location form right now, our onsubmit function is doing the navigation, but it's doing that navigation before submitted is set to true. So I think we'll accept one more prop that can basically do the navigation after submitted is set to true, and then this logic won't kick in because submitted will be true. So I think I want another prop that says onsubmit complete and then this is just a function that returns nothing. And then the parent component can do whatever it wants when the submit is is finished. So right here we will call
props.sonssubmit complete. In onsubmit complete we can actually do the navigation. So if we head back to our edit form we're going to say we have a function called onsubmit complete takes in nothing and this is going to be the thing that does the navigate to. And then we'll pass that down. And then here we can pass onsubmit complete down to the component. Now this is a scenario where you could use emits. Um I think my react brain kind of just kicked in and I made it so that we could pass down a function. Um but as you saw in our our component earlier that search results component, we were using emits to admit that search results were available.
Technically in this case we could also emit an event that says submit complete. For now we're going to leave this as is, but you could use emits if you wanted to. The other thing is we need to do the same thing over in our ad page. So now we need an onsubmit complete function. This just does the navigate to and then we can pass down onsubmit complete. And so that should fix the bug where it says, "Hey, are you sure you want to leave?" Because we actually did make an update. So let's add several more exclamation marks.
Click update. Okay, that at least navigates us away. The next bug is the current location actually needs to be refreshed when that form is completed so that we have the latest data when we get to this page here. So the way we will handle that is at the top level on our slug page here. So right now we are only refreshing the location on mount. And because the ad page is actually a nested route, this component never unmounts, right? It's it's basically mounted the whole time we're here. It's mounted even when we're on this page or on this page.
It just displays that section when we're here, but it technically never got unmounted. So the other scenario where we want to refresh the location is if they navigated to this page specifically. So in this component we can actually detect which page we're going to and if we're going to the top level dashboard page that's when we will refresh the current location. So there is a hook here called on before route update. You can pass it a call back and this gives you access to the route that you're going to. So we can say if the route we're going to name is equal to the dashboard-loation- slug page, then we also want to refresh the current location. Now, just to be sure we're not getting a bunch of extra network requests, let's actually look at the logs here as we navigate around. So you can see here that I I went to this page, I went to that page, but if I head back to this page, it does make the request for Denver. And that's basically what we want cuz if we're ever heading back to this page, it's possible that we were on another page that changed it. So now this makes the request there. If we
instead were to navigate to this page, we see one request for San Francisco that's not duplicated and we can navigate around. But if we go back here, we see that request again. So this is the behavior that we want. And I essentially do want it to be called on mount because that's when it's going to potentially be rendering some of its child routes. But I also want it to be called if we're going back to the top level page of this this sub route. So that looks great and this should fix our issue. So if we go to the edit page and we change the description and we click update that sees those latest updates.
We can head back here update that. That looks good. Let's also try updating the coordinates. So if we head back to Denver, we should be able to head to the edit page and then let's drag this slightly over to the right and click update. And now that updates the coordinates as well. So this is definitely the behavior that I want. And let's just remove those exclamation marks. Get us back to a good state.
Awesome. So if we head to our checklist, where are we at? We did a whole lot. So the location fields are editable. They are pre-populated. They are validated because we're using that exact same form as before. Changes are preserved if the submission fails. So to test that, let's actually just throw an error directly from our backend route. So when we go to put, let's just straight up send back an error and make sure that that actually gets displayed in the form. Oh no. So the moment they make a put request, we're immediately going to send back an error. And that displays as expected and all of the values stay the same. So that's looking good. The loading spinner does show up during update. Uh we can go back to actually just waiting a second before allowing this to succeed. So we're going to pause 2 seconds before allowing this update to happen. So say update spinning spinning spinning and then it redirects. That's exactly what we want to see. So that looks good.
Confirmation dialogue appears for unsaved changes. We know that that's the case, right? So if they drag this and then try to head back, it's like, are you sure you want to do that? Uh same thing if we do a hard refresh. If we were to just change the description here and then try to go back, it would make sure that we can't do that or lose unsaved changes. So that's looking good. And then the save button shows a check icon. we came up with a more interesting icon, but that's the case as well. All right, so there's one more thing we need to fix, and that is for not found locations. So, we actually are handling this at the top level. So, if I go to a location that's not found, it shows not found on this page, but we are showing the sidebar items here. And so, I actually think we shouldn't show these sidebar items at all if the location was not found. So, let's fix that. So, if we head to the main dashboard page, right here is where we're setting the sidebar items. But essentially, I don't want to add these three if the location was not found. So here's what I'm going to do.
So let's set these by default. And then if the current location has a value, then we're going to push those in. So we'll say sidebar store sidebar top items that push those items there. And so now if you are on a location that's not found, it just says not found. And then you can go back to locations. But if you're on a location that is found, you can see that. Now, this will have an effect on when the location here is loading. And ultimately, I think what we need to do is show a loading spinner if we're waiting for the location details.
So, let's actually slow down our API so we can see that in action. So, if we head here where we're getting a single location by slug, let's wait for two seconds. So, now if I head back to locations and then go to a different location, it actually does say loading there in the sidebar because the current value was actually the previous one. But I think if the state is pending, we shouldn't show these at all. So back in the sidebar here where we are showing the sidebar top items, if we're on the specific location page and it's pending, we should show a loading spinner. So right here, let's create a container div and only show this if the current path starts with slash dashboard. So that means we're on a one specific location page and if the current location state or status is pending then we are going to show a loading spinner and we will center this.
So this parent container will just be a flexbox and say items center justify center. So now if we head back we click on a new location we see that spinner there and then all of those show up. So we actually want it to appear below and we don't want to put in these extra items if the status is pending. So if the current location has a value and the current location status is not pending then we'll display that here. And that actually simplifies our logic here. So if we have a value we'll just straight up use the name. Okay. So now if I head back to locations click on a new location you can see that it's loading and then finally we have the information about that location. So that seems like a much better user experience. Okay. So we can update location details. This is looking good. Let's add it. Commit it.
Push it. Move on to the next thing. Next up, as a traveler, I want to delete locations from my list. So, there's a confirmation dialogue to make sure that they know they're about to delete this location. We show a loading spinner and then redirect back to the list of locations. Let's get it going. We're going to check out a branch for ticket number 32. And I think the way I want this to work is if you're on a specific location page, I think we should have like a little threebutton drop-own menu and then you can click on that and then click on delete. And that will pop a dialogue to say, are you sure you want to delete? So for this in Daisy, they have a drop-own component and I think this is what we'll use. Essentially, we'll just have an icon inside of there.
delete locations
That's the three dots. And then when you click it, it'll have that option to delete. So we'll use this. And then if we head to the specific page for location, which is this slug page here, we're going to display this right next to the title. So let's try this here. And then we want an icon. And the size is going to be 24. But let's check out icons and find one of those like three dot menu icons. Search for dots maybe.
Yeah, this this is what this is what I'm thinking of. Dots vertical. That's what we want. Throw this in here. Okay, so that's looking cool. It's a little bit big. Let's do a button small. That's better. And let's also decrease the size of the icon. Let's go to like 20. That's looking much better. And then I want to get rid of the padding so it's just the three dots. So let's add a padding of zero on the button. Yeah, that's exactly what I want. And then the option here will be to delete. And then we can also even add a link to edit. So there's multiple places to get there. So we'll have one option that's a next link that says delete. And then for an icon, I think I want like a trash can because we are deleting. Let's go with trash can filled. Give this a size of 20. And in this case, I think the icon should come before the text. See fresh. Make sure we can get that icon in there. Yeah, that's looking good. And then let's also add the edit location button. So we'll say edit and then we'll use that same icon that's in the dashboard which is the map
pin cog. Yeah, that looks good. So let's just link to the edit page while we're working on it. So this should go to find this. We want to go to the dashboard dash location-slug-edit page and then for the params we can pass in the slug which we can get from route.params.slug. So that looks good.
Now the edit button should take us to the edit page and it does. Now we want this delete button to actually show a dialogue. So if we check out Daisy UI, they do have a dialogue component or a modal component. And this is what we want. They have a few different ways to do it. I think we should just do it with the dialogue element because that's the latest and greatest stuff and it works really fine. So you can pop a dialogue like that. You can have like a close button or a cancel button. You also can click outside to close. I think we'll do it with the click outside. So let's copy the close outside one and then we'll work from there. Let's grab this code and we're going to have multiple dialogues throughout our app. So I'm actually going to create a custom component for this that wraps the Daisy component. So let's create an app dialogue and we'll throw in a template.
And then the way that we actually pop open the modal is by calling show modal, but we'll need a ref to that dialogue. So let's add our script tag. And this dialogue, we'll give it a ref of dialogue. And then we'll create a variable for it. So this will be use template ref and we want to choose dialogue and then the actual button to open it is going to be outside of this component itself. So we don't need this.
Now we don't need the ID anymore because we have a reference to the dialogue. But now I'd like to listen for the dialogue close event because if we click outside the dialogue that should fire the event. Also if we press the escape key that'll fire it and that'll let us know the state of the dialogue. Is it open or is it closed? So when the component is mounted I want to add that event listener. So we'll say dialogue.value.addeadventlister. We're listening for the close event. And then I'm going to create a handler called on close. And this will just be a function.
And for now we'll just log dialogue closed. And we also need to remove this event listener if the component is ever unmounted. So on unmounted we'll do the reverse. We will say remove event listener. Now to see this in action I'm just going to default the dialogue to open. So I'm just going to add the open prop. And so it should appear on the page as open. And then here on our location page, I'm going to add an instance of the dialogue. So right at the end of the component here, we'll say we want an app dialogue. And now we can see when the page loads, the dialogue is there. But if I click outside of it, we can see we get that event that the dialogue was closed. So now I want to be able to control the open and close state with a prop that we pass down to the component. So in the dialogue, let's define some props. And in this case, I want a prop called is open. And this is just going to be a boolean. And now we'll just bind to this open prop. So we'll say open is props.isopen. And so now this should open and close depending on the prop that was passed down. The other thing is we need to be able to
alert the parent that this dialogue closed, especially if they pressed escape or they clicked outside. So we're actually going to emit a close event. So let's define our emit. And we'll just call this on closed. And it won't have any arguments. It'll just fire if the dialogue closes. And now we can use this inside of our onclo. Here we will emit the onclosed event. Now with this we're ready to hook it up on the other side.
So first of all we need an isop ref to pass down. So let's define a ref called is open defaults to false. And then we can pass that down. And then we also need to listen for on closed. And when it's closed we just want to set is open to false. Now let's hook up our button. So when we click this button we want it to set is open to true. So we'll just add a click event listener. set is open to true. So now if I click this, it sets it to true. That gets passed down to the component. The component binds that to the open prop and the dialog will display. But then if I click outside, it's going to fire off the close event.
That will then set is closed in the component to false. And then I could reopen it if I wanted to. So let's give it a try. If I click this, the dialogue opens. If I click outside, it closes. And I should be able to open it again. And I can. Nice. Now I do actually want this drop down to close when we click the button. So we're going to have to write some JavaScript for that. You can see in Daisy UI they mentioned to close the dropdown after click you can use something like document.active element.blur. So we will do just that.
Let's actually create our own method here for opening the dialogue. We'll say open dialogue. We'll define that here that will set is open.value to true. And then here we can say document.active element. We know that this is an HTML anchor element. and we will say blur. And that should remove the focus from that link that we just clicked on. So now if we open the dialogue, that disappears. We can click outside. We can open it back up. Awesome. So now we want to pass in some title text, some confirmation text, and then also have buttons that can be clicked. So if we head back to our dialogue, we're going to have a few more props. Let's have a title, which is a string, and then we'll have a description, which is a string, and we'll use that here. So the title will be displayed here and then the description is here and then we'll work on the buttons next. But let's pass down the title which is are you sure and our description will be deleting this
location will also delete all of the associated logs. This cannot be undone. Do you really want to do this? Right. See how that looks. So we go to delete. Are you sure? Deleting this location will also delete all the associated logs. This cannot be undone. Do you really want to do this? So, that looks good. Now, I want to be able to have a section for buttons. So, I think we should have a cancel and a confirm button, and we'll define those inside of the dialogue. So, let's have a div here.
We're going to flex it and push all the buttons to the right. We'll have a button, and we'll make this an outline button, and this will just say cancel. And then we'll have another button. And we'll give this a class of button warning. We'll also give this a gap of two. So there's a little space between the buttons. And right now we'll just say yes, I am sure. But we'll accept this as a prop in a second. Let's see how this looks. I like that. So if you click cancel, that should close the dialogue. If you click yes, I am sure, that should initiate some action which deletes the location. But let's first hook up cancel. So when you click cancel, we actually want to close the dialogue. So in this case, we'll just call our on close function. So we'll say when this is clicked, please on close.
So that should hook up the cancel button, right? But now let's accept some props for this button here. So I think I want to accept the confirm label is what we'll call this. And then let's also accept a prop that allows the user of this component to set the color. So right here we'll bind the class to be something like confirm class. Let's define these two props. So confirm label is a string and then the confirm class.
We can make a string union. So let's give them an option of like button warning. Let's also give them an option of like button error and button accent probably like button primary. So that seems good for now. If we want to specify other colors, we'll add more props later. And then now let's pass these props down on the other side. So for the confirm label, we will say yes, I am sure. And then for the confirm class, let's do a button error. So it's a nice red button. So now if we click this and instead of saying yes, I am sure, let's say yes, delete this location. Give it one last look and then we'll hook it up. Yeah. So are you sure?
Deleting this location, we'll also delete all logs. Yes, delete this location. That will emit an event that says something like on confirmed and otherwise they can cancel it. Okay. So back in the app dialogue, we'll want one more emit. We'll say on confirmed. And this will have no arguments. It'll just be something that they can tap into. And when they click this confirmation button, we will emit the onconfirmed event. So we'll say emit unconfirmed.
And then we can listen for that in the parent component. So back over here, we'll say on confirmed, we'll say confirm delete. We'll define our function confirm delete. And this is where we will call our API. So, if we head to our server folder, we'll define a new endpoint for a delete against this specific slug. It'll be similar to the put. So, I'm going to copy this, just rename it to slug delete. And we're not passing in any body. It's just going to be a delete request for an authenticated user with this slug. And then we can make the database query. So, we'll say deleted is a weight of remove location by slug. And we pass in the slug. And for now we'll return the deleted item.
delete location api
Let's go implement this remove location by slug. This will be in our queries. So if we head to our queries file, we want to remove a location by slug that takes in the slug and the user ID. We will need to pass in both of those. And the codes will be similar to this. We can say removed return the removed item. And instead of update, we will use delete.
We don't need a set. So delete from the database where we have a location with this slug and this user ID. And so because the user is already authenticated, this will only allow them to delete locations that they actually own because it'll have their user ID set there. Which means if we get back nothing, meaning nothing was removed, then this was not found. So we could return a not found error. But if it was deleted, we actually will get that back and then we'll know that this thing was actually deleted. So over here we do need to pass in the event.ontext do user id. And now we can check this. So if something was not deleted, we should return a 404 because they tried to delete something that they don't own. So let's actually just copy our send error here. And this is just going to be a 404 error. It just says location not found because they tried to delete something they didn't have access to. Otherwise, if it was deleted, we'll just return nothing. Like a 204 no content. So we'll set the response status to be a 204. and pass in the event and that should give
us a 204. So now we can call this API method from our front end. So on confirm delete should be an async function and we can actually call our dollar sign fetch. We want to call API locations/slug. We'll construct this URL and pass in the slug and this will be a delete request. We'll await this and we need some similar loading logic error logic like we did whenever we're inserting or updating. Now I am going to copy that from our location form because it'll be very similar. Essentially we have a try catch we have a loading variable. So I'm going to do something very similar. So we head to our location form. This handle submit is going to be very similar to what we want to do. And instead of all of this we will actually call the API to make the delete. And then we'll need a couple of state variables. one to hold on to an error if there was one when we tried to delete and then one to let the user know that something is happening. So let's create a few refs here. We'll have the delete
error. Make this a ref that starts off as an empty string. And then we'll also have is deleting and that will start off as false. And then we'll use these variables here instead. Now we're not setting errors on the form. So we can get rid of this section. And then this loading value will become deleting value like so. And then we don't need to take care of is submitted. Uh finally we'll bring in fetch error from o fetch like so and then when we are done deleting we will want to navigate back to the dashboard. So after this we'll say navigate to dashboard and once confirm delete gets called we will want to close the dialogue right because they click confirm delete we're going to be showing loading on the main page. So let's actually close the dialogue the moment that this function gets run. So we will say is open set that to false. Now I want to display a loading spinner when deleting is happening. So we'll reuse the same one we already have on the page for when the location is initially loading. But I want to do both. So I'm actually going to create a computed
variable that looks at status equal to pending and also looks at is deleting. So we can have a computed here. We'll call it loading. And this will be if status is pending or is deleting is true. And in this case we will have to do status.value. So now everywhere I was comparing status.value I actually just want to use this computed loading variable. So here if loading is true, here if loading is not true, and then here if loading is not true. And that looks good. And then also we'll display the error message if there was one. And we can actually have another computed value that takes into account either error message. So let's have an error message computed property. And this will be error value. status message or delete error like so. And then we'll use this error message instead down here. So we'll say if error message and not loading, display the error message.
Awesome. So let's give it a try. And to see it in action, let's actually slow down our API so we will see that loading spinner. So for the delete endpoint, let's just add a quick pause like so. We'll wait for two seconds. And now let's delete Dallas, Texas. And the error message is always showing up. I think we got that wrong. So if we head back looking at error message and this does need to be delete error value.
Yeah. So don't forget the dot value. Okay. So now doesn't display but we can try deleting it. Yes, delete it. It spins and then it head takes us back to the list of locations. Awesome. Lastly, let's just test out if our error message actually pops up. So if we head back to the API, let's just immediately throw an error when we hit this endpoint. We will say oh no. And that should pop up when we try to delete. So let's try to delete Houston, Texas. We click delete.
Confirm. Oh no. So if something goes wrong on the server side, that error message will pop up. So all this looks good. Let's add it, commit it, push it up, and move on to the next thing. Next up, as a traveler, I want to create new travel logs for any location. So right now, we have the ability to create locations. Right? We have all these locations across the map. Now, I want to add specific instances when I visited that location, like the date when I went there, the date when I left, and I can keep track of all of that under each one of these locations. So, for instance, if I head to San Francisco, I could add the time that I went to Microsoft Build in 2014 or recently when I went there for GitHub Universe. So, that's going to allow me to add a few more dots on the map here in San Francisco. And we'll see those logs here. So, the form is going to take in the title, description, and the dates. We'll have some validation to make sure that the end date is after the start date and the start date is before the end date. Uh it'll be validated just like our other form. We'll show a loading spinner and have that same confirmation dialogue if they try to navigate away after they've already made
create location log form
changes to the form. So this add location form is going to be on this page here. And first up, we need to make sure that this button takes us there because we added this button a while back, but it's not yet taking us to that page. So let's do that first. And we'll check out a branch for issue number 33. And now if we head to the location slug page, let's link up that button. So that's right here. It says add a location to get started. And we want to turn this into a next link. And this should go to the route with the name dashboard location-l. And the params are going to have the slug, which should be route.params.lug. Format this. And now this button should take us to this page.
And it does. Great. So for this, I'm going to go ahead and start by creating a form that's very similar to our add location page, but this is specifically going to be for location logs. So this is our location form. And let's think about what's going to be different for a location log because we're still going to validate it with the form. I think one of the main differences is we would need to pass in an insert location log zod schema and type. So that would change and then accordingly the types of initial values would actually change here. Submission would be the same except it would have a different type there. And when we're adding a location log, we are going to allow them to set a specific point on the map because the time you visited that location might not be those exact coordinates. It might be like a specific place or point of interest near that location. So all of that looks good. And then on our form, the main area that would be different are the form fields that we pass in here, right? Because for a location log, we would need name, description, start
date, and end date. And then it also has a latitude, longitude. Okay. So after reviewing everything, I think I can come up with a refactor for this that would allow us to reuse most of the logic, but then just pass in a different type. So either it's an insert location or an insert location log. So let's give it a go. So I think we'll reuse this, but we'll make it so that we can use it for both the locations and the location log table. So I'm going to rename this component to be the location base form.
And then we're going to need to take in a type argument. So in view, if you want your component to take in a type argument, you can use generic here. And here we're going to say t is our generic type. And then everywhere we have insert location as a type, we'll use t. So that should be fine there. And then we'll use t here. And then we're going to want to take in a zod object. So let's actually take in the schema as a prop. So this will be of type zod schema which gets imported from zod. And then we'll pass the schema in here. So this will be props. schema. And we won't import insert location anymore. See what else do we need to update. Yeah, we should say that our type extends a latl long item, right? So if we remember back in our types, we do have this type which is just two properties latl long. And we know that both a location and a location log has a lat and a long property. So let's actually say t extends a latl long
item. We'll import that in as well. So now that should get rid of the error of attempting to grab long and lat. And we're still getting this error here. So what I'm thinking is instead of allowing initial values to be optional, it just has to be passed in from the other side. That way this logic of setting a default name and description would have to happen on the other side. So let's actually do that. Let's just only allow them to pass in the initial values and then we'll just set that directly here as props.initial values. And that should work. So this is looking good. Now let's try to create a location form that uses this location base form. So let's create a template.
And this area right here, I want to specify differently depending on the type of form. For location form, it needs to be these two. But in view, what you can do is use a V slot. So I'm going to pull these out and then just specify a slot like so. And now when I use the component, I can pass in some children and they'll get rendered right there in that slot. So in the location form, if I specify these two fields here, those are going to get rendered into that slot.
Now, these form fields need access to errors and loading. So what we can actually do is send some scope down to this slot. If you look in the view docs, they have this idea of slot props. So we can actually add some bindings here. So if we set errors to be our errors object and then we set the loading to be our loading object, now we can get access to those two things inside of the slot. And so whenever we're creating an instance of it, we can say vlot and then get access to those. So here we'll say v slot and we should be able to dstructure it to grab the errors. There they are and loading. Okay, so that's looking good. But then we also need to pass down our other props as well. So I'm actually going to copy the props because they'll be very similar except we'll just have some default values that'll be specified. So we'll have our script define our props. This does not take in the schema. This takes in the initial values which is of type insert location.
So we'll import that in and this can be optional because if it's optional we're going to specify the default values to pass down and then we'll pass this down here. So we will say the initial values is bound to props.initial values and if it does not exist then we'll pass in those default values and we can reuse those default values that we had earlier. So if initial values are not passed in then name is empty, description is empty and then latl long is just center USA and then we'll import in center USA from our constants. So the initial values now get passed down and what's nice about the generic typing here is because the way we define this we said that the initial values is of type t that is getting its type from here. So now everywhere else we'll expect type t to be the type that we just passed down here. And so in this case t here should be of type insert location. And then we can pass all of that down. So we'll pass down the onsubmit. We'll pass down onsubmit
complete. We'll pass down the submit label. And we'll pass down the submit icon. And then the last prop we need is the actual schema validator. So here we'll pass down the schema as insert location. And right now we're only importing it as a type. So this is getting a weird error. We need to import it both as a type and as a value like so. And I think we've done it. So now the other components that were using location form can pass down all the same props that they were before, but we're reusing this location base form. So let's confirm. If we head back to our app, we should be able to go to the add location page. And if we refresh, still getting rendered out. Let's try adding a new location. Let's add Tokyo again. So we'll search for Tokyo, set it, and then add it. And it got added. So I'm actually very surprised that that refactor worked. But uh essentially we we've now all of that logic is hidden in here and we can reuse that for location log. But this is now being used by both add location and it should be used by
edit location. So if we go to edit this should prepopulate and it does. Let's make sure the description work. We can update it and it updates the description and when we go to edit it that is included there. Okay. I am very happy with this refactor. It's very fun to use generics like this. But the beauty of this is now we can reuse this for our location log and all we have to do is specify the form fields, create the API endpoint, and we don't have to worry about all the logic of the form. So that's a beautiful thing. So let's create a copy of this. We're going to call it the location log form. And what's going to be different is that we're pulling in insert location log and using that in each of these spots instead. And we are going to have to go create that schema. So let's do just that. So if we head to location log, we need to use zod to create a validator for this table just like we did with location. So we're going to do something very similar. Going to copy this out, specify it here. We'll need to bring in create insert schema from drizzle zod.
We'll validate the latitude and longitude in a very similar way. We'll import Z. In this case, there is no slug to omit. So we won't so we will not omit that. We still want to omit the user ID. In this case, we can also omit the location ID and then just set it on the server side because in our API, the endpoint could be locations slug slash add and that will add a location log to that specific location. And in that case, we could get the location ID via looking up the location by slug. So, let's actually omit the location ID from the request and we'll handle that on the server side. So, that is omitted. And we need to make sure that we pass in the location log table here. Okay, so this is looking good. I think I want to remove some duplication because I did just copy paste this schema from the location table. But each one of these is a ZOD validator. So we could actually pull it into our our schemas section of our app. So let's do that. So I'm going to pull these out and then they'll be
nice and reusable. So in our ZOD schemas, we can just specify all of these here. So we're going to have a we'll call this the name schema and in this case we can just do a zstring because we know it's a string. We'll do the same thing for the description schema. We'll create our lat schema and our launch schema. Okay. And then we'll reuse these in both of the zod validators. So here this will be our name schema. Import that in. This is our description schema. also import that in.
This is our lat schema and our long schema. Nice. So those schemas are nice and reusable. We don't need Z imported anymore. And then we can also reuse those validators on our location table. So here we have name description latl long. Import those in. Cool. So we we've reduced some duplication there. So this is looking good. But now for the location log, this needs to be called insert location log. Let's not confuse that. And then let's also create the type based on this schema. So we'll export the insert location log type which is going to be z.infer type of insert location log and we will import zod spell that correctly. Okay. So now this file exports the vad validator and it exports the type. So we should be able to use this now in our location log form. So, if we head back to the location log form, it now is accepting an insert location log. And we're getting a nice validator here because we're potentially missing two properties, right? We're missing the start date and the end date. If we look
back at our schema, our ZOD validator is validating that started at and ended at cannot be null. So, this is likely complaining that we are missing the started at and ended at properties, which is great. It means our all of our our types are working wonderfully. So let's actually pull in the start tid at and let's just set this to yesterday. So let's do date now which gives us a time stamp and then subtract 24 hours. So 24 hours * 60 minutes * 60 seconds * 1,000 milliseconds should give us this exact time yesterday. And then we'll set the end of that time to be date.now like so.
Okay. Um now we can specify all of our form fields. So, we have a name. We have a description. We also will need a started at and ended at. So, we'll have started at. This will just be a text input. We're going to want to grab errors. At this will be ended at. Label will be ended at. It's going to be a text input. And we want the error from errors.ended at. Okay. Now, we are going to want these to be type date. We'll need to set that up next. But let's just make sure that this form actually works.
So now that we have the location log form on the location slug ad page, we want to create an instance of the location log form like so. And we have a couple of props we need to pass down like onsubmit, submit complete, and submit label. So the submit label will be add location log. The submit icon will be I don't know. Let's look it up.
So let's look for uh map pin. Let's see what our options are. I like the the map pin with a plus. So, we'll use that one. And then the other props we need are onsubmit. We'll create our own function here called onsubmit. Create our script tag. We'll have our function onsubmit that takes in the values which are of insert location log type. And then for now, we'll just log those out. Be sure to import this in. Make this async. And then we also need the onsubmit complete. We'll call this submit complete. This will be another function. And when we're done creating a location log, we probably just want to go back to the location itself. So we can do a navigate to and the name we want to go to is dashboard-loation- slug. And then we'll pass in the slug. The slug here will be wrap rams.lug. And we'll be sure to get access to the current route with use route. Okay, that should do it. Moment of truth. We're going to head back to
the app. We refresh and we want to go to the add location log page. There it is. Um, it's working. So now we have a name, a description, and a started at and an ended at. So yeah, we have all of our form validation. Um, let's see if we can get those values logged out. So uh, let's specifically add a time that we visited San Francisco. So we're going to add a log. We'll call this Microsoft Build 2014. And I'll say I saw the net compiler become open source. And now that we have all the fields filled out, we can try adding it.
And they logged out. We're not sending it to the API yet, but they are being validated and logged out. So now we can send them to the API. Now, one thing I'm noticing is when we go to this page, it is actually setting the marker as center USA all the time. And really we want to set those initial values instead of them being center USA, they should be the initial values of the location. So at least our marker starts on San Francisco. So for the location log form, I'm going to go ahead and pass down these values directly. So that way I can get access to the current location inside of the ad page. So I'll just copy this initializer and we'll pass down initial values. So our initial values will be this, but instead of center USA, I'm going to get access to the current location. So we can use our location store that gives us the current location. So we'll say use location store and we can grab current location.lattcurren location.l long. Now current location can be undefined but because of the way we set up serverside rendering you'll never make it to this
page unless that value actually exists. So we'll still pass in center USA but I do want here want to say current location.long or that and then current location.lat or that. And we can use optional chaining here. Yeah. So that should give it that default value. And then we can also pull in center USA.
Like so. Now when we go to the add location log page, the center marker should be on the location that we're adding a log for. So if we head back to San Francisco and then we go to add a log, we can see that it adds the marker there, which is exactly what we want. Now, I do want it to zoom in a little bit more. Let's actually look at our map store and see how that's being handled.
So if we go to stores and then map, this is giving it a zoom of six. I think I want to go further and I think we'll pass in a zoom value so that way we can be specific about it because by default it'll zoom to six. But let's add another prop on new value just like we did before. So if new value has a zoom level which will be optional and a number then we'll use that. So here we'll say new value zoom or default to six. Yeah, that could be undefined. Sweet. And then for the location log form, our default zoom value whenever we add the point should be closer. And so this is actually happening in the location base form. I think I could take this in as a prop, right? Because right here, this is where it's setting that added point. And I want to set the initial zoom value here.
So let's just hardcode it here. Like if I set the initial zoom to something like 11, let's see what that gives us. I like that much better, right? Because if we're adding times that we visited San Francisco, it's going to be much closer to that that point that's in San Francisco. Okay. Um, so I'm actually going to accept this as a prop. So that way both the location log and location form can set what the default zoom value should be. So let's take in zoom, which will be a number, and we'll pass that down here. This will be props. Zoom. And then when we create an instance of the location form, we'll use that default value of six like this. But for the location log form, we want a zoom value of 11. That should do the trick. So when we're on the location log form, that zooms in there. But if we're on the add location form, that should just be a zoom level of six. Yeah. So this doesn't zoom in as far, but if I'm adding a time that I visited this location, it does zoom in much further. And I think we
actually want that closer zoom level when we're editing the location. So we should be able to pass it in there as well. So right now the location form is defaulting to a zoom of six. So we could accept a zoom prop that's optional. That's a number and then use it if it exists. Otherwise default to six. So we could say props.zoom or six. And then in the case where it's the edit form which is here, we could pass in a zoom level of 11. And now when we go to edit a location, it zooms in much further because it's like that actual location.
But if we go to add a location, it doesn't zoom in quite as far because you'll have to find that location. So I like this behavior that we can customize it in that way. Now while updating this, I'm seeing we are getting a type error here for the edit location form. And one of the issues is that the current location could be null whenever we're loading that data. So let's only render the form if the state is not pending and it actually has a value. And we still get a type error and that's actually because it's not optional like it is in the schema. So earlier when we extracted the schema, we did not make description optional which it is. So in order for this to line up with our table definition, we need to say that description can also be null. So let's just say or z.null null because in our table definition description is either text or null because it's it's nullable.
And then same thing for the location log the text here should be nullable. And the reason we got that error is when we extracted this out, we were no longer chaining from the field, right? So the way that this was written before was grab the field which already is nullable because it's inferred from this type up here and then we gave it a a max value.
So this is a nullable string. But when we overwrote it, we did not include that null type. So that's why we're getting the type error. That should fix the error over here. And it does. Awesome. And now that I'm thinking about it, we did do a lot of refactors. So let's go ahead and just run a type check. Make sure that nothing else popped up with all of this refactor. And we're looking good. Awesome. So now let's get back to adding a location log. So if we head to San Fran, that zooms in. We want to add a log that zooms in a little bit closer.
And now let's get this date selector working. So, we're passing in a number, but we do want this input to be of type date. Now, if you look at Daisy, they actually do have a calendar component. This is new in Daisy version 5, and it's nice and styled like Daisy UI, but it does require some setup. You'd have to install one of these libraries. They have a few different to. There's this peak a day, and then also Cali. I'm actually just going to use the built-in date picker built into the web browser because it should work fine for our purposes. Now for this we actually will create our own custom component because if we take a look at form field it is doing things that are specific to input and text area and it's handling all the details of like when the value changes and when to set the value. But in the case of a date field we actually want to have the underlying value be different than what's actually being displayed.
Right? because the underlying value is a time stamp, but the thing we display to a user is an actual date format. So, we're going to create a component that displays the date format, but under the hood, it's actually setting that field value on the form to be a timestamp number. So, let's actually copy our form field component, and I'm going to create a new one called date form field. and it's going to accept all the same props, but instead of using a field which comes from validate, we're just going to use a regular plain old input. And now we don't need self-closing. Now the type in this case is always going to be date because this is a date component. And then we'll always give this the input class by default like so. So this is looking good. We've got a base input that's a date type. Now we actually want to handle taking in that number value and then displaying it as a date on the input here. So we're going to take in a value that is a number and then we want to let the form know that this is the initial value for this particular input.
Now built into validate is a hook called use field and you can pass in the name of the field that you want to operate on. So we're going to pass in props.name and you can pass in some initial values. So here the initial value will be props.value that got passed in and then from there we can use all of the things associated with the field. So the first thing we'll do is just tap into that blur event. So on the input here, we can hook it up and we'll say when you blur from this input, handle the blur like so. So all that looks good, but now let's actually tap into the change event of this input. So we'll say when the value changes, let's create a function called date changed. And right now I just want to log what that actual value is. So we'll have this function date changed. It takes in the event which is of type capital E event. And right now we're just going to log out event.target target. And in this case, the target is an HTML input element. So we'll say the target is
event.target as an HTML input element. So that way we can access the value property and we don't need to destructure that because we're just grabbing that property directly. Okay. So whenever the value changes, we'll log it out and we'll see what the browser actually sets for the format. Now let's use this component instead of our app form field. So, if we head back to our location log form. Now, instead of an app form field, let's use the app date form field, both of these, we'll pass down that initial value, which in this case is just going to be started at and ended at. And I'll actually just move this to my template so I can access it directly. So, this will be initial values this. But now that it's there, I could use it in both spots. So, I can pass down initial values started at. And then we'll do the same thing with ended at. Okay, let's refresh. So now we have a date picker. Let's open up the dev tools. And if I select a date, you'll notice that it uses this specific
format. So year-on month- date. That is what an input is expecting if you want to see that value reflected on a date input. So what we need to do is take a date timestamp and convert it into this format. So for this I have this handy function called format date. Now you could install a library for this, but I'm just using a plain old date. It's not too complicated. Essentially, take that number that is the time stamp, convert it into a date. Then get the year, get the month, which is zero based. So add one to it, pad it with a zero, get the day, pad it with a zero, and then create that formatted year, month, day item. So now we can actually use this whenever we're passing that value down. So use field also exposes what is the current value of the field.
And so that we can grab from value. I'm going to rename it to input value so it doesn't interfere with our props value. And then on the input itself, we're going to pass down that value with our format date function. So I'll say format date and then pass in the current value of the form. Now the type right here is unknown because we do need to type this use field. So here I can set that this is a number and then that should be happy because we're actually passing down a number. And with that, it should actually display date whenever the page loads. Like so. Because we took that timestamp, turned it into something that the form would like, and now it can actually display it. But now we need to handle when it changes because when it changes, we need to convert it back into a time stamp. So also built into use form is a function called handle change.
And we can call this with what we want the value to be. So right here in our change listener, target.value value is always going to be that string with your month date. So what we can do is we can call handle change and then convert that string back into a number. So we'll create a date object pass in target value and then call the get time function that will get get it back as a time stamp. So now if a user selects a new date that's going to convert it to a time stamp update it on the form itself and then the underlying value will still be a time stamp. So, if I change these around, you can see the date is still reflected, but behind the scenes, it's still a time stamp. So, if I submit this, we should see that started at and ended at are timestamps even though they were displaying as those date values.
Okay, so that's looking good. Let's look at our checklist to see how we're doing. So, we've got title, description, and dates. We have required fields are validated. That is already handled, right? If we try to submit without a name, we see that. And we already have confirmation dialogue appears for unsaved changes because if I for instance change this and then go back that is still handled but now let's do the date validation. So ensure that the end date is after the start date. Now for that we'll do it in our zod schema.
So if we head to our schema for location log, we want to update this location log validator here to make sure that the end date is after the start date and the start date is before the end date. Uh now built into zod is a method called super refine and this will actually give you access to the fully validated model.
So then you can compare two properties. So here we can pass in a callback. This gives us back the validated values and then we can write our custom logic. So here I can say if values started at is greater than values.ended at then we have an error or if the values.indended ended at is less than the values started at. We also have an error. Now the way we can add errors is with the context and we get access to that here as well.
So this context then allows us to add issues. So we can say add issue and then specify the issues that exist. And in this case it's going to have a code which comes from z.zad issue code.custom. So it's a custom issue. The message here will be start date must be before end date. And right now we're only importing Z as a type. We want it both as a type and a value. So that looks good. And then we also specify the path. So Zod knows which field this error is associated with. So let's add this to the started at field. And then we can add another issue in the same way, but we'll just say end date must be after the start date. And this path is ended at. So now with this extra bit of validation, we should see it on the form if we choose dates that are after or before. So if I set the started at to be in the future, start date must be before the end date. And now that that's the
16th, if I set the end date to be the first, then we see end date must be after the start date. So if we head maybe to the 29th as the start date and the 31st as the end date, we can see that that gets validated. So we're validating the dates. Now we need to insert it into the database. So let's work on the API endpoint. Now I want this endpoint to be at API/loations/slug/ad because you're adding a specific log for that location because you're adding a specific log for that location. So in server API locations, we'll add a new folder called slug. And then inside we're going to create an add.post.ts. So this method will allow you to send a location log to be inserted into the DB. Now this will be very similar to when we were creating locations. So let's see what we were doing over here. First we validate it.
create location log api
Then we send back the error. Then we were doing some other validation. And then ultimately we insert it. So we definitely at least want to do this. We want to validate the incoming location log. So here in slug add post we are going to define our authenticated event handler. We'll be sure to bring that in. And then we're going to use the insert location log schema. So we'll import that in as well. So if it wasn't valid, we're going to send back an error. We'll import our utility to do that. And then we should check to see that this location log actually exists with that specific slug. So if we take a look at our git route, we are doing just that.
We're finding the location with this slug and that user ID. So, we're going to want to do the same thing here. So, we can exit early if it doesn't exist or if they don't own it. So, let's import in find location. And if this location was not found, we will send back a 404 like so.
And then if it was found, we'll validate it. And then if it was valid, then we can insert it into the database. And so to insert it, we're going to need the body. We'll also need the ID of this location because if you remember earlier, we removed the location ID from the ZOD validator. So we'll pass in location ID and then we also need the user's ID because we're creating this location log for that user. So here I want to return insert location log.
We'll pass in the location ID. So this will be location ID. The location log insertable. So this will be result.data. And the user's ID, which will be event.context do user id. And that should have a lowercase I. So, insert location log. And now I need this query. So, I'm actually going to create a new queries file for my location logs. So, let's create a new file. Call it location-log.ts. And in here, we'll have this function insert location log.
That's going to take in the location ID, which is a number. It's going to take in the location log to be inserted in this case, which is of type insert location log. We'll import that from our schema. And then lastly, we need the user ID, which is a number. Now, for this, we're going to grab the inserted data. We'll await a call to our DB. So, we'll make this an async method. And this will be DB, which will importinsert. We'll pass in the table, which is the location log table. And the values that we want to insert is that specific location log. And we will return what was just inserted. And right now the thing we're trying to insert overlaps with the name from our schema.
So let's actually call this the insertable pass that here. And then we will import this from our schema. Now it's complaining because we do need to attach the location ID and the user ID. So right here we're going to spread the values of insertable also pass in our location ID and then also pass in the user ID. And now Drizzle is happy. And then from there we will return the inserted value. Let's make sure that we export this. And then over on the other side, we can import it. Import this in.
That looks good. And now let's try calling the endpoint. So if we head to the add location log page, this method here now actually needs to call the API. So here we just call cesurf fetch with the location with the API endpoint. So in our add location log page, it's going to be very similar. So we bring in cesurf fetch. We have the values. We're now going to make a post request to slash ai/loations slash slug. So this is going to be route.params.slug slash add and this is going to be a post request. So we're adding a new location log for this specific location. We're passing in those values and then when the creation is complete, we'll navigate. If there was an error, we're reusing all of that form logic. So that should display for us. Let's give it a go. So, let's head to San Francisco. Let's add a location log. Let's call this GitHub Universe
2024. I will say attended comp with the syntax team. And for the location, it was actually over here. I forget what this is called, but it was this is this was the venue. They had like two big buildings right here. So, I'm going to throw the marker there. And then this was last year in October, and it was the 28th through the 30th. like that. Moment of truth. Add. It didn't error out, but now we need to take into account if there actually are location logs. And we did get redirected back to this page and it should have queried San Francisco with all of its location logs. Let's actually call the API directly. And yeah, so it's being included in there, but our logic I thought we set this up before to only show this if the list of locations was empty. I think we have a bug. Let's take a look at our location slug page. Yes, this link needs to be inside this div. So only show that button if we don't have any locations.
Okay, so we're on our way. We're actually putting location logs into the database. This is great. Now the loading spinner should show. Let's actually slow down our API again just to make sure that that is happening. So let's head to our server API. Add a little slowdown. So we'll wait for two seconds. And now we're going to add Microsoft Build 2014.
And this was at the Mosone Center. Let's see if this search can find it. Moscone Center. Did I spell that right? Yeah, that's the one right there. There it is. Um, so that looks good. It did update the name here. I guess it would be a good user experience if we have an option that says like set name or don't set name. That's okay. I'm okay with typing it again for now. So, there's that. And then I'll say everyone got a free Xbox, which is true. Every single attendee got an Xbox. And it was actually a pain to figure out because a lot of companies don't let their employees receive gifts, but I convinced my employer to let me keep the Xbox. Um, I actually have no idea when it was.
It's probably in the summer. I'm just going to say like June. I could look up the date, but that doesn't matter right now. So, let's just head back to 2014 for the end date, and we'll say it ended in June, and it needs to be after the start date. So, yeah, let's let's say it's those dates. We can always go in and edit it later on once we add the edit page. So, we'll add this. We do see the spinning. That's what we were testing right now. And then it gets added. We still need to list those out as cards. Eventually, we'll show them on the map, but we are getting much, much closer. Lastly, I just want to make sure that the error state works here. So if this endpoint errors out, is that error displayed? And it should because we're reusing all of that same logic. So just say, oh no. And now if we try submitting the form, well, it needs to be valid.
And then we try submitting. Oh no. Okay, so that's awesome. Sweet. So that's it for this one. Let's move on to the next one. All right. Next up, as a traveler, I want to see logs for each location. So we were adding them to the database in the last story. Now we actually want to show all of them in cards on that specific location page. So right here we'll display cards very similar to how we have cards on the main page. So let's check out a branch. This is ticket number 34. And then let's take a look at how we're listing those cards on the main dashboard. So here in dashboard location index is where we have those cards that are the locations. But we're going to have a very similar functionality on the location log page.
list location logs
The only difference is we're actually displaying the log name and description and not the location name and description. So I think I actually want to pull this out into a reusable component so that way we can reuse it on the location log page. So I'll grab this nux link and then in our components let's create a location card. So call it location-card.view. We'll have our template. Paste that in. Now we're not going to repeat over the locations in the component itself. We're just going to pass the location down. This looks good. And then let's think about our props. So, we're going to need where are we going to? We'll also need that specific item so that way we can update it. And we'll need access to the map store. So, let's set up our script first. Let's get access to the map store. So, we'll say use map store. So, we have that. Now, let's take in a two prop. So, we'll define our props and two will be a route location raw. We'll import that in from view router. Then we can just pass that in directly like so.
And then we're going to need an item that has a name, a description, a latitude, a latitude, longitude, and ID. So name, description, latitude, longitude, ID. Do we have anything in our types that describes that? So name, description, latitude, longitude, ID. So really, this this is a map point, right? So we're taking in a map point here.
Let's actually add that as a prop. And then we won't even need to bring in the route location raw. We can actually just grab a map point because that has a two property on it. So we'll import that in use that instead. And here we can say our map point. And then we can pass our map point in there and in there. And here we can say map point.name and map point.escription. And then right here whenever the mouse enters we're setting the selected point to be the map point that was created from that location. But now since we're just passing down a map point, we can just directly set it equal to that map point like so. Okay, so this looks good. Now let's actually use this component. Uh, and I am realizing so since we're not using props in the template, we can just call define props.
And then down below, we don't have to say props.map point. We can actually just access map point from the props. So that looks good to me. Let's use this component in the dashboard. So if we head to our dashboard location index now instead of all this we want to add a location card. We want to repeat it for all the locations and give it an ID. And then our map point will just be a call to create map point from location. Pass down our map point like so. And that should be it. So now we can get rid of all this. And if we head to the dashboard page, it should show all those cards in exactly the same way. Let's give it a try. So we're back at the dashboard. These cards appear like they should. I can still click on them. Now we have a nice and reusable component.
Awesome. So now let's reuse that component on this page. So we can actually list out the logs here. Now before we do that, there's one more piece of reusability and that's this set of classes right here. So this is what allows that container to have overflow and scroll and I want to reuse that on the individual location page. So I'm actually going to extract this out into just a reusable class. So if we head to our assets directory and into our main.css, we can use the at@ apply keyword with Tailwind to use all of those classes. So let's create a new class called location list and we'll use at apply and then apply all of those CSS classes. So now I can reuse location list on the dashboard instead of that list of classes. And so that should behave as expected as well. So if we refresh this, still looking good. Now we're ready to use it over here on the individual location page. So I'm going to copy this div and then if we head into location slug.view this is where we have access to the list of location
logs. So right now this element displays if there are no location logs. So if there are no location logs we have like the add to get started. Essentially we want a div right below that that we should display if there are location logs. So here we'll say only display if location logs has a length right here like so. So if the location exists and it has logs then display all of these cards. So this is going to be a location list and then we want to repeat over each log in the current location logs. For each one we'll pass down the ID and then we need a new helper method that will create a map point from a location log. So we'll have a similar function. It'll be create map point from location log. It takes in that log and then creates the map point.
So if we head to our utils, we have one for map points. Basically, I want one exactly like the one above, but it takes in a location log, which is of type select location log. Pull that in. And this returns a map point. It's going to be very similar. In this case, it spreads the location log. The label says view. That's fine. And then we're going to direct them to the individual location log page. So, this will be dashboard-loation-lug-. We haven't created this page, but we'll create a a placeholder page in a second. And then the parameters we want to pass down are the ID of the location log itself. So we'll say ID is location log ID. So that looks good. Right now is probably compa complaining because this page doesn't exist. So let's just add a placeholder page. So inside of the slug folder, we want to have another file called ID with brackets.view. And so this will be the specific log of that location with that slug. So we'll add a template for now.
just a little header that says this is the location log page. Okay, so now that page exists, this link should work. That creates the map point and we're listing them out here. If I refresh, there we go. So now it's actually listing out those location logs and it already has that that hover functionality because we extracted that out into a component. But if I head back to the location page, these still work, but I can click in here. So that's looking good. Um, I will mention I had to restart my dev server.
I actually didn't pick up on the refactor of creating that create map point from location log function. So restarted the dev server. Everything's looking good here. I think one thing I want to do is make sure that this has a similar height to this page here. You can see that there's not as much breathing room below. And that's likely because we have a description on this page. So let's actually increase the default height and then reuse that in both spots. So if we head to the main dashboard, this has the class padding for min height 64. I think I want to do a min height of 72. And then we'll actually extract this out into a reusable class so we can use it on both of those parent elements. Let's call this the page content top. And then in our CSS, we'll create another reusable class called page content top. We'll apply those classes. And then I want to reuse this class inside the individual location page. And so right here, instead of padding for min height 64, we'll add that. Save it. Now it's got a little bit more breathing room. And then
when I head back to the locations page, it's the exact same height. Awesome. But I caught one bug that I didn't see in the template. If we head to the edit location page, it actually still lists out all of those logs. So we only want to list out the location logs if we're on this main page here. So if we head back to the location slug.view page, just have a bunch of v ifs. We'll need to make sure we put it in the right spot. So right now we have if the route name is not the main dashboard location page then have the next page there. We actually want to do a very similar thing for this list of cards. So we only want to show the list of cards if we are on dashboard location slug. So here we'll say if route name is equal to dashboard location slug and we have a list of location logs then we'll display those cards. I'm just going to put this on a new line so it's a little easier to read. Now, those won't render out when we're on the edit page or the ad page, but they do render out when we're on the overall page. So, that's looking good.
Let's check our checklist. So, we have the loading state because that was already happening for the current location. We have that empty state. If we head back to a location like New York that doesn't have any logs, we're showing that empty state there. Now, we need logs sorted by date. So, we can actually handle that on the server side.
So, if we go in here, they actually are sorted by oldest to newest, but I went ahead and added a few logs in Denver, and they're in all sorts of order. So, I I have several different spots here, all like shows that I went to last year or different cool places. And right now, these are just in the order that they got created. But, I actually want to list these with the most recent visits at the front of the list. So to demonstrate that, let's actually make sure that we show the date range on these cards. So in order to get those names to show up, I want to put them at the top of the card so they appear right above the title. So first, if we head to the location card, essentially I want a section where the consumer of this component can just put whatever they want because we don't have a top area whenever we're rendering it on the main page. So right here, I'm going to add a slot and then I can give it a name and let's just call this top. And now whenever I'm using this component, I can say what we should render in this spot
right here. So whenever we have an instance of the card here, I want to show the visit dates. So for that we can use a template and then there's this vlot prop. And then I can specify I want this to appear at the top. And now this will render out in that top section. And for this I just want a paragraph tag.
Let's show the log.st started at and then also we'll do a slash with the log.ended ended at. So, we'll show both the start date and the end date. And then we'll give this some styles. So, I want this to be text small. Let's make it italic. And also do a text gray 500.
And now we see those dates at the top there. As you can see, they're timestamps. So, we are going to need to format them. But this is great because I can render that out at the top here. But then when we're on the locations page, that slot isn't used. So, it just doesn't display at all. And that's definitely the behavior that we want. Okay. Let's get these to show up as actual dates instead of just timestamps.
So for that, I want to reuse the format date function that we used in our date form field component that we had earlier. So we look in our components, this date form field in here is this function called format date. And this just shows it as year, month, day. I want to reuse that on the card. So let's actually pull this out. We're gonna pull it into the utils folder. And we'll just create a new file called format date.
And we'll make this the default export. Like so. So because this is in the utils folder, it should be autoimp imported over here. So we can use it inside that date form field component. But now we'll have access to it over here. So right here I want to show format date and format date like so. And now we have some nice readable dates. But one more thing is if the start date and the end date are exactly the same because that's what it is. If this was just like a one-day event, which most of these are, I actually just want to display the start date. So let's add some custom logic right here. We'll just put this in a span and we'll say if the log.st started at is not equal to log.ended at then display both of them. Otherwise only display the started at date. And now you can see it's just the start date and then there's an event here that spanned multiple days. So it shows the start date and the end date. Okay. So now that we're displaying the dates, let's actually sort them so that the most recently visited ones are at the front. And you can see that the most
recent visit was the Tao show that I went to at the end of last year. So we want to make sure that that one appears at the front and all of the others are sorted by their visit date. So if we head to our API endpoint, this is going to be get one specific location by slug. This is using the find location function in our queries. And right now we're just including the logs, but built into Drizzle is to a way to query this further. So here we can say order by and we can specify which field we want to order by and in this case we want to order in descending order. So we'll use the descending operator. So it's most recent to oldest and we'll use fields started at. So when did we visit that spot and just like that when the data is received from the server side now that's actually sending it back in sorted order. So we see the most recent visit here and then our oldest visits are on the end. That's exactly what we want.
And if we look at San Francisco, should be exactly the same way. Nice. So, both of those are looking good to me. Let me add this. Commit it. Push it up. We'll move on to the next thing. All right. Next up, we want to see those location logs listed in the sidebar. So, just like we have all the locations on the main dashboard, when we go into an individual location, we should show all the logs in the sidebar. And those will be displayed right here, just like we have the locations listed out there. So getting this working should be fairly easy because we have all of this set up in our locations store. So if we take a look in our stores locations, right about here is where we create the map points and the sidebar items when we're on the overall dashboard that has all of the locations. We want to do the exact same thing when we're on one individual location. So I'm actually going to copy this logic and we'll just update it to use the list of location logs instead.
list location logs in sidebar and on map
So we'll put that there. But now it will be current location.loation logs and then we'll iterate over each log. Now we already created that utility function create map point from location log. So that's good to go. And now we'll update the ID. So this will be location log-log. ID. The label will be log.name. And the two prop will be dashboard location slug ID. And then we'll pass in the ID to the params.
So this will be log ID and that should do it. So if I refresh now, you can see first of all it's a twofer. We we were listing them in the sidebar, but we automatically get them appearing on the map because we're just updating the list of map points. So if we head back to locations and then go to Denver, we should see all of those points on the map as well. And if we click on them, that takes us to the log page.
Awesome. So, actually, if we look at our list of stories, uh, we are also doing this one. As a traveler, I want to view all the location logs on an interactive map. And really, we just got it for free because of the way that we set up our store, right? Our data is very similar. So, the code to add it to the map was very similar as well. So, this is showing the those location log markers.
They're appearing on the map and then they're also displaying in the sidebar. Now, one more thing I want to do is make sure that the titles here don't take up too much space. You can see that this one is two lines. So, to get this working properly, let's actually just make sure that it cuts that extra text off. So, in our sidebar button component, which is here, when we render out the label, let's actually just add the truncate class. So, this comes from Tailwind, and it does a few things. It sets overflow to hidden, sets text overflow to ellipses, and then also says whites space no wrap. And so if we do that now, it doesn't appear on two lines. We kind of just show that that dot dot dot, which is what we want. So let's look through our checklist. Empty state shows when no logs exist. That should be the case. If we actually head back to locations and then go to a location that doesn't have any logs, you see that they're not listed there. But I do believe we actually need to make sure that that area displays as loading. So let's actually slow down our API endpoint. So we can see what happens when we switch from a location that has
logs to one that doesn't. So in our API folder when we get a specific location log. Let's just wait two seconds like this. So if I head back to locations and then I go to Denver, takes about 2 seconds. But then you can see all of the logs for Denver. But if we go back and then let's say click on New York City because it's taking a second for all of that data to load. Those old location logs are still visible and you were seeing that list of logs up at the top as well. So, we need to handle it in two spots. First, let's handle it on the card here because we shouldn't display that list if we're also pending. So, if we head back to our location slug page right here where we're listing over the cards, we also don't want to display that if the status is pending. So, we're checking that here. So, we have we have this computed loading variable that we can reuse. We'll just add that to our conditional. So, only list out these cards if we're on the dashboard page.
and we're not loading and we have logs to iterate over. But now we also want to show that loading state in the sidebar. So we're actually already handling this in the store. We just didn't take into account the current location that's loading. So if we head to our locations store right now, we have sidebar store loading equal to if we are currently getting those list of locations, but we also want it to be loading if we're getting the current location. So I'll say if the current location status value is equal to pending. And so now when I go between the locations, that area should actually show as the skeleton loader. Let's do a hard refresh. And if we head back to let's say Denver, now we see this area as loading. And then it loads all of those in. And then if I go back to like New York City, all of this is loading. And then the data finally shows up. So that is the behavior that I want. So we have an empty state when no logs exist. We're showing that loading indicator. We're displaying those log entries in the sidebar. They have a title and an icon. It updates when the
logs change. Now, it should because that's the behavior in the rest of our app. But let's try adding a location log to New York City. So, I'm actually going to add when I lived there for one summer. I I believe I was like in this area like in Kips Bay. Yeah, like some somewhere somewhere around there. I'll say I lived slashw worked here one summer. And that was probably around 2018. Yeah. So, if we add it, it should appear on the map, appear in the sidebar, and appear on the cards. So, we add it. Everything's loading. And there it is. It's in both spots. Sweet. But, I did notice one bug. And that is when we go to a location that doesn't have any logs on it, it actually zooms in to the last spot that we were in on the map.
And we don't want that. So we need some logic that says, "Hey, you still should focus in on this area, but there are no points to be displayed." So that actually happens in our locations store right here. We're setting all of the map points after iterating over all the location logs. But if there are no location logs, then we still need at least one point on the map so that it will zoom in over there. So let's do just this. So we'll say if map points.length is a thing, then set it to be all of those points. Otherwise, we'll have the same logic as we had before where we just set it to be the current location. So, we'll add current location value like so. And so, now if we go to a location that doesn't have any map points, it still zooms in because we we have that initial marker there. But the moment we add a location log, so I want this to be let's say like right here.
Let's call this JSNation 2023. So, we'll add it. And now that point appears there for the one log that I visited. But if we go back to let's say Seattle where I haven't added any logs yet, you'll see that it then zooms over here. But we we actually caught one more bug there where if the data is loading, it zooms in on the wrong spot. So one thing we'll do in order to prevent zooming in on the wrong spot before it's done loading is if we head back to our location store, if we are in a loading state, then let's actually clear out all the map points.
So that way there's nothing confusing there on the screen. And then in our map store, if there are no points on the map, we should just zoom out kind of so that everything is visible. And that way when the data is done loading, it'll zoom in on that spot. So if we head back to the map store, kind of already have this logic here where once those points are set, we set the bounds to be the points that got added. But let's just say if there are no points, then let's just fly the map to the center and way way zoomed out. So, let's just say map.map.fly to for this. Let's set the center to our center USA constant and then set a zoom level of two. So, now when we bounce between locations, everything will clear from the map.
It'll zoom way out and then zoom back in once the data is loaded. Let's give it a try. So, we loaded here on Houston, but if we go back and then let's say we want to go to Seattle, everything clears out. It centers and then when it's done loading, it zooms in on those points that it's able to center on. We can try again. Let's head somewhere over on the other side of the map like Amsterdam. It zooms out. It's waiting. And then those points appear. So that's the behavior we want. Okay. So all of that is looking good. Let's double check our other story. So as a traveler, I want to view all my location logs on an interactive map. We have that loading state. It shows the right zoom level, right?
Whenever we pick a location, it's going to zoom in on that location with all of its points after it's done loading. Like so. That's that's what we want. And the log markers are correctly positioned, right? So, these are all the the different spots that I've visited here in Denver and they are definitely in the right spot. Awesome. So, we got two for one. We closed ticket 35 and also ticket number 39. Let me add it, commit it, push it. We'll move on to the next thing. All right. Next up, we want to view location log details. So, I should be able to click in the sidebar or in a card or in a pop-up, and then that displays the specific title, description, and dates for that location log. And then eventually this is the page where we'll add images for that specific time that we visited that location. So right now we do have the links working right. If we click on it, it's kind of just this blank page. This is where we want to display all of those details. And we can get there from any one of those links. So just like we're storing the lo of locations and the current location in the location store, I think we also want to have the current
view location log
location log. So we'll duplicate that logic. So let's get back to the main branch and then check out a branch for TL36. And then if we look in our locations store, this is where we're going to want that logic. So just like we have a computed that has the current location URL, we want a computed with the current location log URL and then we're also going to have a use fetch that gives us the current location log set up in a very similar way. So first up, let's set up our URL. So we'll call this the location log URL with slug and ID. At this point, it's almost like enterprise Java, but I do like some descriptive variable names. And this will be locations/lug slash ID. So this will be route.params ID. Okay. And then similarly, we want to set up a use fetch with all the same stuffs, but we're going to call this the current location log, current location log status, current location log error, and refresh current location log. And here we want
the location URL with slug and ID. And this is going to give us back a single location log. So we'll call this select location log. Now let's expose all of these from our store. And now we can use these on the location log page. So very similar to the location page, we can grab all of this stuff from the store and then display the loading state and everything else on the page itself. So if we head to location slug id, we'll add our script tag. But now we want to bring in the current location log, current location log error, current location log status. We'll call this the location log. And let's display our loading state and then display the name and the description. So very similar to the slug, we're going to have all of this here with loading error message and then the name and description. So we'll display that here. And we're going to need a very similar loading computed in
here. So let's actually just create our loading variable which is a computed property. Right now it only cares if the status value is equal to pending. But in a bit when we're deleting an individual location log, it'll care about that too. And then we need a computed for our error message. Very similar. Right now it's just coming from error value status message. So that gets rendered out there. And now we can look at the location log instead. So if the route name is dashboard location slug ID and the location log does exist and we are not loading then please show me that location log name. We'll get rid of the drop downs for now. We'll add those whenever we can actually delete this location log. But we'll just display the name and description and give it a go.
So if I head to location Denver/3, nothing displays and even the sidebar is empty. So so there's a couple of things we need to do. First of all, we need that data available if we're on this specific URL. And if you remember, because we're doing serverside rendering, we always want to request that data at the top level. So, if we head to our top level dashboard, we actually have an if statement here that's looking to see what page we're on. And we basically want to have another list of the location log pages.
And if we're there, we're going to refresh the current location log. So, let's create a new list of pages. Let's call it the current location log pages. And this will be dashboard location slug ID, dashboard location slug ID edit, and dashboard location slug ID add. Now, these two don't exist yet, but they will. So, that looks good. But then we'll also make that request at the top level. So, when we're on the dashboard, if the current location log pages has this specific route name, then we're going to refresh the current location log. And that's that method that we just exposed. And so now that data should be available when we go to the individual page and that endpoint doesn't exist. So right now we're trying to request it. Of course it's not found because we need to actually create an endpoint that pulls the data for that specific log. So to the API we want a new endpoint which is get locations slug ID. So we'll call this
ID.get.ts and this will be for finding a single location log. It's going to be very similar to finding a location, but it's for location log. So, I'm going to copy this logic here and this will grab the slug and then if the location exists, make sure that that log exists. So, we'll have the location log and we'll create a new query called find location log. We're going to pass in the ID which comes from our router params.
So, we'll grab that right here. This will be the ID. Say get router param for ID. And we want to make sure that this is a valid number because we don't want to query our database with a string for the ID because it exists as a number in the database. So let's just do a some quick validation right here. Let's just say let's bring in zod and we want to validate this to coersse it into a number and then we can do a safe parse.
We want to pass in that ID and then if that success is not true then that means the ID in the URL was not a valid number and we'll return an error accordingly. So let's do a very similar thing here. We'll set the status code to 422 and we'll say invalid ID. But if the location exists and the ID is valid, then we can go grab it. If it doesn't exist, then we return a 404. Just say location log not found. And then finally, if we were able to get it from the database, we will return it. Now we need this query find location log. So if we head to our queries, we have our location log. Right now we just have insert. We want a new one. Find location log. They give us the location ID and the user ID. So we'll have our found log. This will just use db.query. We can go to the location log table. We'll find the first one and then we'll pass in our query with where. So find the first one
where the location log ID is equal to this ID that we're passing in. And the ID that we're passing in is the one in the URL. So that's actually a location log ID. I'm just going to rename it to ID because we're finding this log by ID. So, we'll do that. So, find the log with this ID and find the one where this user ID is the one that owns it. So, we can pass in the location log user ID is equal to this specific user's ID. Now, we'll need to make sure that we import equals from Drizzle OM. And this actually needs to be an and query. So we'll say and also from drizzle OM where the ID is equal and the user ID is equal like that. And once we've got it we'll return it. If it didn't exist that will just be undefined. And then on the other side if it was undefined we send back a 404. So let's import this in and then ID at this point we've already validated is a number. So we'll just cast it to a number. Okay. So now when a request
comes into API locations slug ID, we'll look it up. If we found it, we'll return it and we should see that data on the front end. So let's do a refresh. And now we see Kasa Bonita. Very good. Now I realize we still have that slow loading state for this specific location. So if we head to the get location by slug, let's remove that that two second delay.
And now we don't see that loading spinner locally because everything loads pretty quickly. Uh, but now you can see we're in a pretty empty state because none of the sidebar links are here. We need to set all of that up. So, if we look back at our ticket, um, clicking a log in the sidebar card or pop-up takes us to that page. So, that should be working. Let's actually start at the homepage. So, our our sidebar is populated. So, if we go to Denver, we can click on Tao live. That takes us here. And we need to make sure that we request the latest data because right now it's only requesting it on server side render. But when we go to this page, we also want to refresh that data.
So on the page itself we can listen for unmounted very similar to what we were doing on the slug page. So on this get location by ID page when it is mounted we will say location store dot refresh current location log. And so now as we navigate between the different logs it's always going to get the latest one. So that shows that show and then if I go to this one it shows that one and if I go here it displays that one. This is looking good. And now I'm also realizing that I copy pasted that weight of 2 seconds. So that's why clicking on these actually does take a second to load in.
But we are getting the data which is what we want. And of course if we go back to the list, clicking these should take us to that same page too. And then also clicking in the card takes us to that page as well. So that item is done. Uh we also need to display the dates, right? So we are showing the title, the description. Let's get the dates displayed in there. I'm going to do a very similar thing to what we did in our cards. So on the page where we're listing out those cards, really just want this logic here. We could extract it to a component. I'm not going to. I'm just going to copy paste it. So right above the name, we'll display that information here. And all of this needs to be location log like so. But now we should get those dates on this page as well. Awesome. So we can check that off.
Now we can work on the sidebar. So when we go to a specific location log, we don't want to see all of the top level logs anymore. We just want to see links associated with this one specific log. So I should be able to edit this location log and then I should have a menu where I can delete this location log. So if we head back to the main dashboard, this is where we're setting up those menu items. So we request our data at the top and then here is where we're setting those top level items. And we just need another branch to say if we're on the current location log pages, then we'll set up go back to Denver or go back to the the location page. And then we'll have a link to edit this location log. So else if we want to look at current location log pages, if that is the current area that we're on, current location log pages. And so in here, we'll have similar logic because when you're on the individual location log page, we do want to display a link that takes you back to the overall location. So I need the location to
exist as well. So I'm actually going to request that at the top level here. So um if we are on the current location log pages as well, also get the current location. So that way the location will exist when you're on that specific location log. And that means we'll have access to the location name. And we can do something very similar. So I'm going to copy this if statement. The main thing we want is to be able to go back to that location. So this should be link location and it will say the location's name and take us back to the overall map with with all the points of that location on it. And for now, let's get rid of these links. But in a bit, this is this will be the spot where we can add more links. And instead of displaying the map icon, let's actually display a back button. So, we'll use that same back button that we have when we're on the other pages. We'll go here and we can update the label. So, the label could say back to location name.
Let's do that. Like so. So, now when I am on a specific location by ID page, that's what I want to see. I want to be able to get back to the the Denver page. And then when I click here, um I want that to be cleared out and only show that item. So instead of pushing, I actually should just overwrite this with a single array that has one item inside of it. And that should give me the logic I want cuz I'm on this specific visit.
Shows me all my details. I'll have some links where I can edit this specific visit. In a bit, we'll add images to this specific visit. And then I can go back to our Denver page, which has all of the other times we visited Denver. But I can click on a specific one. That will load and we can get to it here. Now, this is one more area where we need to clear out these items here. So, if there is a current location log, I don't want to display all of those links. I only want those to be displayed if I'm back on this page here. So, we can handle that in the locations store as well. Head to the store right here. If we're on the current location log pages, then we can just clear out those sidebar items. So, we'll also add that here. So we'll say else if the current location log has a value and we're on the current location log pages then we can set the map points to be the current location log and we'll clear out those sidebar items. So let's say the sidebar store sidebar items just has nothing inside of
it. So now if I go to an individual page it clears all of that out. This is the only point on the map because this is the specific time that I visited. But if I go back to the overall location, everything else pops up. And then I can dial in to one of them as well. So that's looking good. And this is the behavior that we want. So let's add it, commit it, push it. Next up, we'll work on actually editing an individual location log. So I should be able to update the description, the title, even the visit dates if I want to. And of course, let's not forget to remove that artificial weight that we have in our API. So here at the top, we can remove that 2- second weight. All right. Next up, we need to be able to edit log entries. So, it's it'll be the same as the ad form. It's just it will be pre-populated very similar to how we had the edit location form, but this is going to be for specific log entries.
edit location log
So, for example, when I'm on this page, I should have an edit button, and then I can change the title, the date, description, and coordinates. So, first up, let's get a button in the sidebar here that links to the edit page. So if we head to our dashboard component. So right here is where we have that back to location name button. We also want a button that says edit this specific location log. So we will call this the link edit location log. The label will just be edit log. And this will take us to the dashboard location slug ID and then edit page. So dashboard location slug ID edit. and the slug will come from there and the ID will also come from the params. So for this we'll create a folder called ID with brackets and inside of there I'll create my edit view file. Give it a basic template then a title. This is the edit log page and
then make sure that it works. So yeah, that shows up. I can click on it. That takes us to the edit page. Let's change the icon and we'll use a similar icon to the edit location page. So we'll use this map pin cog like so. So that looks good. And now we want that edit page to appear on the side just like it does for all the other forms. So we're handling that down here and we're saying if it's in the edit pages then it should appear there. So let's go here and let's also add the page for it. So this is slug idedit. So now it should appear on the left and it does. So that looks good.
But we do need one more link that will just take us back to the overall description with the card. So when we're adding links, we want to add the current location log. I'm going to put that link right above the edit. And this will just say view log. This takes us to dashboard location slug ID. And this will just be a map pin. Great. So now we can go here.
We can go to the edit page. We can go back. Wonderful. Now, we need some nested routing because when I'm on this page, we want to render out a nested route inside of the ID page. So, if we look at our top level ID page right now, this has the loading spinner, the error message, and then if we're on the slug ID page, it shows the specific information. Otherwise, I just want to render out a next page. So, let's have a div here, and then we'll say v else have a next page. Okay, so that is going to render out when we're on the nested page. And now we should see this is the edit log page pop up. And we do. So that renders the nested page. This renders the overall page. Looking good. Now we want to show the form on this page. So we'll need an instance of our location log form, but we're going to provide it some initial state. So let's take a look at how we did it for the add location log page. Just going to copy this. And then on the edit page, we'll render this out. But then we'll need to bring in the
store to repopulate everything. So first up, the label should say update location log. And then instead of a plus button, let's use the same one we did for the edit page here. So this is map pin up. That makes sense. It like has an arrow pointing. Then we'll need to bring in our state. So let's set up a script. Inside of here, we're going to need the current location log. So we can grab that from the store. Let's copy our imports here. That'll be there. And then this location log is what we want to pass down as the initial values. And we already have our loading state in the parent component. And we essentially don't want to render this form unless the log actually exists. So we'll say v if location log has a value. And now it can't be null. And then we can pass that down as the initial values. And then we'll just have our onsubmit. This should take in the updated values which is of type insert location log. For now we're just going to log it out. And then we don't need the status or the error in here because we are handling that in the
parent component. And this does need to be async. And then lastly, we have our submit complete. And this is what will take us back to the location log page. So when we're done submitting, we'll say navigate to. We want to go to the route with the name dashboard location slug ID. So go there. And then for the params, we'll pass those in. We'll grab the router for the route. So we'll say use route. And then we just want to pass in the ID which is route.params do ID and then also the slug which is route.params.lug. And now because we've done all the hard work of setting up this reusable form when we go to this page it should pre-populate with all of the values. And it does. So we can go here. We can go to the edit page. It's pre-populated. We can go back. Choose something else. Go to the edit page.
It's pre-populated. So all of that refactoring work we did earlier made this feature very very easy. Now all we need is a backend endpoint to actually save the changes to this location log. So we will head to the server folder API location slug and then we want an ID.put. So we're going to make an update for the location log with this specific ID. So I'm going to copy the get one and then just rename it to put. And then let's go through our logic here. So everything will be very similar. We're going to first make sure that this location by slug exists. We're then going to validate that that ID is a number. And then once both of those are the case, we now should be able to say update location log with that ID, the user ID, but then we need to also pass in the update. So we're going to need to validate the incoming body. So before we even look up the location by slug, we can just validate the incoming body. So let's actually copy our logic for whenever we're adding a log. It's going to look something like this. We'll bring
in send zod error and we'll bring in the insert location log. Okay, so validate the incoming body. Make sure that that location actually exists. Make sure that the ID is a valid number and then we'll update it. And we'll need to pass in the updates. So we'll just pass in result.data which is the validated body.
Now we need to create this update location log which eventually will be imported from that location log file. So if we head back to our queries location log, we need one for updating. So right here we're going to get access to the updatable and this will actually be the location log ID because we're going to update where that is the ID and it has this user number and these are the values we're going to update it with. So we'll say the updated item. We're going to call our DB. We'll say update. We want to update the location log table.
We're going to pass in our values which is going to be the updatable. So we'll spread updatable. And then we'll need a wear query to look for this location log ID and this user ID. So we'll say where and we will copy our where statement from find location log. So where the location log ID is equal to the lo this specific location log ID and that user ID update these specific values. When you're done with all that, we'll return the updated value and we do need to say returning here. So we get what was updated. Now this could come back as undefined because if for whatever reason someone tries to update a log that they do not own then this will just return undefined. So on the other side when we call it here if we didn't get anything back then that means they tried to update something that doesn't exist or that they don't own. But if they did update it we send it back. Now we just need to call it from the front end. So right here we'll need to bring in our curf fetch and then it will be very similar to editing a location but in
this case we're editing a location log. So we want to call API locations slug and then ID. We'll grab this from route.params ID. We're doing a put. We're passing in those values. This should be it. And I'm kind of reiterating, but this is the benefit of refactoring the code the way that we did earlier. Each new feature we add just requires less and less code because we were able to think about how we would use this in other places. So if I've done everything right, we should be able to make this update. So let's refresh the page. We'll keep an eye on the network and let's just try to change this to an exclamation mark. We'll update it. And it looks like it sent the put request. Let's look at the request.
Yeah, so it sent that question mark, got it back. But when we went to this page, it didn't show the latest value. I think we just need to make sure that we refresh when we go to this page because if I do a hard refresh, it does have that value. So when a user enters this page, we need to just refresh and make sure that we have that latest value. So back on the ID page, we need to say that if we are entering this page, then we should update it because technically the component was already mounted. So this code isn't getting called here. So I'll just say on before route update and the other place that we did this was for the specific location with this slug. And here we're saying if we're coming to that specific page, then do the refresh.
So I want to do a very similar thing over here. So right here we'll say if we're going to dashboard location slug ID then refresh the current location log. And this should be all we need. I'm going to comment out the onmounted because this should still be called when we head to this page. So it should work for all scenarios if we're going to this page initially or if we come to this page from some other page. So let's do a hard refresh. And here we'll try to edit it. Change it to a single exclamation mark. Click update. We see that single exclamation mark. I should be able to also like change the location slightly.
So, let's update it to there. And now it's slightly south of where it was before. So, this is looking good. Just to be sure, we'll put it like right there. Click update. Yeah. So, that easy. We can we can edit. We can view. Of course, we should just test. Can we also update the date, which should be possible. And I'm noticing a bug here that has to do with time zone values, but we're not going to worry about that right now. Click update, and that updates that as well. We can head back.
Wonderful. This is it. It's It's so easy to crud. Look at that. All right, let's check our checklist. So, all the fields are editable. Existing content is pre-populated. Validation prevents invalid updates. That should still work, of course. So, if we try to just update it with an empty name, it's going to prevent that from happening. We have this prompt to say, are you sure you want to go back because you have unsaved changes. So, that looks good. And there is a loading spinner. Let's just slow down this endpoint. make sure that we have all the right loading state and everything else. We can also test out the error state and then we should be good to go with this ticket. And now I can remove this this onmounted call. So if we head back to the API first, let's just slow it down. So we'll wait for 2 seconds that should allow us to see all the right loading state. So if we go to edit, add some exclamation marks, remove some exclamation marks, and then update.
So we see the loading state. It then takes us back over to this page. Fantastic. Now let's of course test out the error. So let's just immediately send back an error here. We'll say oh no. Make sure that that error pops up. We'll go to edit. And then we see the error. Okay. So this is looking good. Let's add it, commit it, push it, and move on to the next thing. All right.
delete location log
Next up, we should be able to delete log entries. So this will work very similar to the location page. We'll have a menu where they can click delete to delete that specific log entry. And that menu should show up right about here. We'll have like a three dot they can click and then choose to delete. So let's check out a branch. This will be ticket number 38. And now I think we'll copy that menu that we had on the location page. So if we go to the specific location page here, we have this menu. It's a drop-own. It has that delete which opens the dialogue and then there's also the edit. So let's grab this and then I'm going to pull this into the individual log page. This will also appear right beside the name. So I'm going to throw this right here. Uh right now we don't have a dialogue. Let's just make sure the menu works and then we'll get a dialogue onto this page. So now we have this three dot menu. We should click delete and then that will show the dialogue. They can confirm and delete.
And then let's update this to take them to the edit log page because the code we copy pasted took them to the location edit page. But we want location slug IDedit. We need to pass in the slug. And then we'll also pass in the ID route.params. ID. And now I should be able to click this. That takes me to the edit page. I can go back here. I can click delete. So, let's get that dialogue brought into this component again. I'm going to copy it from over here. We need an app dialogue. Pull that down below everything. And then we need the is open state inside of this component. So, we'll say is open. This is a ref that starts off as false. And then we need the function that actually calls the API when they confirm the delete. So, we'll define that here. Make this an async function. Confirm delete.
For now, we'll just say confirmed in the console. Make sure everything is hooked up. Let's update the text. So, this says, "Are you sure deleting this location?" We'll delete all of the associated logs. Do you really want to do this? So, here, let's just say deleting this location log cannot be undone. Do you really want to do this?
Yes, delete this location log. So, that looks good. Now, let's make it so that when we click the delete button, it opens it up. So, we'll say when we click this, we'll say open dialogue. And I'll actually copy what we have over in our other component and we'll put this here. That should open up the dialogue. And then if that works, we'll create the API function. So delete opens the dialogue.
Are you sure deleting this location log cannot be undone. Do you really want to do this? Yes. And at this point, we would call the API. So I'm going to copy the logic for confirm delete because we're going to have a few extra state variables. Now, this is another spot where we could actually refactor this into like a reusable delete component. I'm okay with copy pasting this. It's it's not too crazy. So, this will make the delete request to API locations slug and then ID. So, route.params. ID. And we do want to go back to the specific location, not to the dashboard. So, this is going to go to the dashboard location-slug page. And we'll pass in the slug which is route.params.sl slug.
And then now we need two state variables. The delete error and is deleting. So delete error is string starts off as nothing. And then is deleting is a boolean starts off as false. But now we can use these values in our computed variables. So the loading should be if is deleting value is true or if the state is pending. And then the error message should be if there is a delete error value or uh there was an error actually requesting this specific location lock. So that gives us those two values. They're represented here since we're using that computed variable. Now we just need to bring in fetch error from oetch like so.
And now we just need a delete endpoint. So we head to our API. Now we need a delete for this specific one. Let's copy the get rename it to delete. And the logic is very similar. Make sure this location with that slug exists. Make sure the ID is valid. And then if it is, we will delete it. So here we'll say the deleted log is delete location log with that ID with this user ID. If nothing was deleted, then it wasn't found. And otherwise, we'll send back a 204 no content. So we'll just say set response status to 204. And now we need delete location log. So we'll head to our queries. Have a function delete location log. This takes in the location log ID and the user ID. And we'll grab the deleted. We'll say db.delete from the location log table
where we'll use the same wear query. So where this ID is the location log ID and it's owned by that specific user. We'll return what we deleted and then return it from the function. So if something got deleted, it'll be available on the other side and we will then just return 204 no content. But if we weren't able to delete anything, we'll just say we didn't find it. So this should be good.
Let's import this in and hope for the best. So let's just head back to Denver. I want to delete Kasa Bonita. And then we have a bug. So earlier we removed that onmounted code. Apparently we need both. We need onmounted and did you just navigate to this specific route? So we head back to that page. Let's just add back the onmounted code to refresh the current location log. So we'll say unmounted, we also want to grab the current location log. Now that'll make sure that when we go to this page for the first time, it's there. If we go back now, we get the latest data for the one that we clicked on. So that that makes sense. But let's say I want to delete Kasab Bonita. We go delete. We say yes. It's loading. We're back. And it was removed from the map. Awesome.
Now, now that I'm looking at uh this list, this really should be like live shows or or live music in Denver. Um, so let me actually delete Elich Gardens as well. So, let's delete this one. Confirm. And then let's actually edit this to say Denver live shows 2024. So, these are all the shows I went to in 2024. In Denver in 2024. Update it. Now, the name is nice and descriptive. We go back to locations. It shows up there as well. This is This is coming right along, everybody. We're doing it. We're building an app. Okay, let's double check our checklist. So, we have our confirmation. We've got the loading spinner and it takes us back to the location page after deleting. All right, that's it for this one. Let's add it, commit it, push it, move on to the next one. All right, we're in the home stretch. One of the last set of features I want to add here is the ability to upload images for specific logs. So if we head into a location and then we head into one of the specific logs, I want to add images from this time that I saw Tao live and then I want to add images from
minio local s3 storage setup
the time that I saw all these other bands live and also for these other locations for the specific times I visited. I want to add images to those. Now for this we are going to be using S3 compatible storage. Now, S3 originated with AWS, uh, their S3 buckets, but since then, a lot of different services have spun up that support the exact same API. So, you can actually use the AWS SDK in your app, but then swap out your storage provider. Uh, this site, S3 Compare.io, has a bunch of these services listed. Of course, AWS is the most popular with their S3 buckets, but you can also use things like Cloudflare.
So, Cloudflare has Cloudflare R2. You can store stuff there, and there's a bunch of other services as well. And so you can use any of these services, but when we're working with our code locally, I want to be able to upload to a bucket without needing to talk to the cloud. And for that, there is a project called min.io. So you can run this in a Docker container. It can run completely locally. You can use the AWS SDK and upload items to it. But then when we deploy to production, we can choose where we actually want to store items.
But when we're running locally, we can just store them inside of min.io. So we're going to get this set up locally. Now, to get minio running locally, we will use Docker. Now, I know for a lot of people, Docker can be intimidating. I actually have a video here on the syntax channel that kind of breaks it down for developers, talks about everything you need to know. So, for this, we are going to set up Docker locally. Now, if you don't want to do this, you actually can just go set up an Amazon S3 bucket or a Cloudflare R2 storage bucket and then just talk to the cloud directly when you're working locally. That's completely fine. But, I do want to be able to work locally. So, I'm going to set up this Docker container. Now, if you look in the minio docs, they have a section on getting up and running with Docker. They talk about environment variables that are available to you and a few other things you'll need. And they actually give you this command you can run here. But when I use Docker, I like to put things into Docker Compose. That makes it super easy for the next developer that comes along to just spin this up with a single command. So, we're going to use Docker Compose and kind of like replicate this inside of our Docker Compose. So, first up, just make sure
that you have Docker installed and running. You can see here I'm using docker desktop. So that's running in the background. Now let's create our compose file. So here in our directory let's create a file called docker-mpose.yml. And now we can describe our services. And for this we have a single service. It's the minio service. So we have this services key.
And then we can give it a name. In this case I'm just going to call it min.io. And then we can specify the image that we want. And this is the image name that comes from Dockerhub. So you can see in their initial command up here they're pulling from min.io/minio. io/minio. If you search DockerHub for minio/minio, this is the image that we want to pull down. So here I'm going to say grab the minio/minio image. And in this case, I'm just going to say grab the latest one.
And then we need to tell it what ports to listen on. So we'll say ports. And the first one is the API port. So minio exposes an API. And this behaves exactly as the S3 API behaves. And you need to specify what port that runs on. So we're going to create an environment variable in ourv called minio api port and then we need to map that to a port running inside the container and inside the container the API is running on port 9000. Now minio also provides a web dashboard and this is where you can go in and configure things in the UI just like you would like in the S3 dashboard and so we'll need to tell it what port to run this on. So we'll have another environment variable called minio console port and this runs inside the container on port 901. So this looks good. In a second, we'll actually add these values in our own.env. But let's keep on moving. The next thing we'll need to set up our environment variables so we can set up this environment key.
The first one we'll need is minio root user. So this is the username you'll use to log into the minio dashboard where you can create secrets and keys. And then we'll also specify this in our environment file and we're going to call it min.io root user. We then need another one called min.io root password. And again we'll specify that in ourv.
And then lastly, we specify the minio server URL. And we'll be using this inside of our next app cuz this is the endpoint that we're going to call to actually upload these images. So internally, we'll have an environment variable called the S3 endpoint. And that can be reused throughout our app to know where we make these requests to. And then when we deploy to production, we can set this S3 endpoint to be the R2 Cloudflare endpoint or the AWS S3 endpoint. So that will exist in ourv as well. Next up, we want to tell it where to store its data. And in Docker, these are known as volumes. So we're going to have one volume here that just points to the data directory inside the container.
So I want this to just exist in this folder. So I'll specify a relative path. I like to put my stuff in a folder called Docker data. And then inside of there, give it the name of the service. So in my folder here, there's going to be a Docker data folder and then a minio folder. And then everything minio needs is going to be stored in there. And then we'll map that to the data directory that exists at the root inside of the container. So anytime the container goes to store files here, they're going to be actually stored in our directory here, which means if we ever delete the container and spin it back up, all of that data will still be available. Next, we'll give it its start command. So once the container has spun up, we need to specifically start the minio server. So to do that, the command is server. We'll then pass in the option to say what port the console should listen to, and this is called console address. And we're just going to set this to 90,01, just like we have it set here. here. And so this is the port inside the container.
And then we can tell it to put all of its data in that data folder, which in turn will put the data in our current directory. Now, the last thing we'll do is add a health check. And this will just run in the background to let us know when the server is actually up and running and ready to start uploading files. So we can specify the health check option. And to test it, we're going to run a command. That command is going to be mc. So mc is the minio client. It's a command line tool for interfacing with this minio server. So we'll run mc. The command we want is ready and local. So this will just run in the background and when this returns a successful response, we know that the Minio server is up and running. For the health check, we can set the interval to 30 seconds. We'll set the timeout to 20 seconds. And then we'll set retries to three. So it's going to try three times, waiting 30 seconds between each one to see is the Menio server up and running.
And this should be all we need. Now I'm going to specify these values in myv file. So right here, we'll specify all three of these. The minio root user and password can be whatever you want. It's just the thing that you use when you're logging in in the min.io web console. So I'm just going to set this to minio minio. It's going to tell you that this isn't a secure password, but that's okay because this is just when we're running locally. And then the server URL locally is going to be localhost. So this will be httplohost.
and we point to port 9,000 because that's where the S3 API is available. And this actually needs to be S3 endpoint cuz that's the variable that we'll be using internally. And then finally, we need the ports. So, minio API port and minio console port. Now, I'm going to set these to be the same ports as they are inside of the container. But if for whatever reason you already have something running on your computer that's running on port 9,000 or port 90001, then you can specify different ports here. Just make sure that this port lines up with what's set for minio API port. So with all of this, we've specified everything that's needed for this docker compose file. And when we spin it up, docker is actually going to read this.env file in automatically and it'll pass all of these values in when the container first spins up. So if we head to the terminal and do docker compose up, it will find that docker compose file and then attempt to spin it up. But you can see I got an error. So root user and root
password need to be longer than what I specified them as. So I'm just going to change it to min.io admin for both of them instead of just minio. Now with that updated in myv, let's try again. All right, so it's spun up. You can see the API is available on port 9000 and then the web UI is available on port 90001 and then it's using that username and password minio admin.io admin. Let's give it a try. So, if we head in our browser to localhost 90001, this is the min.io dashboard and this is where we can configure all of our stuffs. So, if we specify the username as minio admin and the password as mino admin, that logs us in and we can start configuring things. Now, since we're storing all of that minio data in this folder, we do not want to commit this to git. So, from the command line, if I do a get status, you'll see that it potentially wants to track that docker data folder. We don't want to commit this. So in our git ignore, we'll just add docker data and make sure that nothing in that folder gets committed to git. So that way each
developer that pulls our codebase down, they're going to have their own docker data folder. And one more piece of config we'll need is to ignore any changes in this docker data folder. So as this container is running, it's going to be changing files in there. And right now, nux would actually watch that folder for changes, and we don't want that. So in our nux config in the vit section we can add some options here. So we want to tap into the server option there is then an option for watch and then we can specify ignored and so this is an array of strings. So I just want to say ignore everything in the docker data folder like so. And now when the next dev server is running it's not going to pick up on any changes in that folder. So, if we head back to our dashboard, we've set up the container.
It's ready to go. It's running in the background. Now, we need to create a bucket. And this is essentially a folder where all of our images are going to be stored. So, in here, let's create a bucket. I'm just going to call this bucket images and leave all the default options and click create bucket. So, now this is the bucket that we will upload to. Next up, we need an access key and secret that we will use with the API to actually upload images here. So, in the dashboard, if you head to access keys, you can create a new one. Now, you can leave all of the default options. Of course, you could set expiration and name, especially if you're going to be using this for more than just this little app when we're running locally.
But again, this container is just for our app. It's not hosted anywhere. It's just a place we can upload our images to when we're running locally. Now, when you click create, that'll show you your access key and secret. Copy those and then we're going to add them to ourv. So, we'll click create. And now, I want to add these to myv. And I'll create two environment variables. So, we'll copy the access key. I'll create a new environment variable called S3 access key. And then we'll also have one that's S3 access secret with the secret value in there. And make sure you write it down because you won't be able to see it again after this. You could of course just create a new one, but the moment you close this, that's the last time you're going to see that secret. And these are the two values we're going to use in our API to upload to this specific endpoint. So, back on our checklist, we have a key and secret.
We've updated ourv with those S3 credentials. And then one last thing we'll do is set up the bucket region. So in the minio dashboard, if you head down to configuration here, you can see that it has server location. Now, this is completely optional, but we want this to mirror what's going to happen when we're uploading in the cloud. So I'm actually going to specify this as US West-1. And this will be an environment variable. So that way when I set up storage when we're working in the cloud, I can also specify whatever our server location is there. So I'm going to save this. We'll restart the instance, but I'll also add this to myv. So, we'll have another environment variable called S3 region, and we'll just set it to whatever we set in the dashboard. And one last one is we'll add the S3 bucket name. So, we'll say S3 bucket, and we called our bucket images. So, we'll just call this images.
Now, all of these environment variables are going to be the ones that we actually set up when we're running in production. So we'll create an R2 bucket or an S3 bucket. Get all of these values from there. And when we're running on Verscell, we'll specify these to be our production values. But when we're running locally, these are all of the values. And now that we have these S3 environment variables that are also going to be required in production, we should add them to our type safe env. So if we head to the lib folder in our env file, let's add them down here. And these are all going to be strings. So now when the app starts up, we'll make sure that we have all of these specified. So with all of that, S3 is set up locally and in the next story we can actually start uploading images to that specific bucket. Now when we're uploading an image to an S3 bucket, there's two ways to go about it. One way is for our client to upload the image directly to our server. So in Nux, they're in the same app, but this is essentially the client making an API request and sending that image directly to the server. then this server could
s3 image upload flows
resize the image or validate the image, do some various things and then upload the image via the S3 API to that S3 bucket. Now, this is definitely the way to go if you want to do your image resizing on the server. But the one issue with this is your server is going to incur bandwidth for this because every image that gets uploaded that is data that's traveling to your server and then that server has to upload that data to your S3 API. So right now we're deployed to Verscell and that means that we're going to have some usage costs for every single image that gets uploaded to our server that's running on an edge function. The other thing about this is because this is an edge function, you could run into time constraints if it needs to do the processing on the server because that edge function could time out. So the way we'll handle this instead is with pre-signed URLs. And the way this will work is our client will first make a request to our server and ask for a pre-signed URL. And in order to create that pre-signed URL, we need the AWS secret and the AWS key. So the
server uses the secret in the key to get a signed URL from the S3 API and then returns that back to the client. Now with that signed URL, the client can upload directly to the S3 API without needing to know our AWS secret. So this is a short-lived URL. You can set an expiration on it. And essentially this URL is a special URL for uploading that one image and then the client can upload that image directly to the S3 API which then puts it into the S3 bucket. And this is the way to go especially if you don't want to have all of that bandwidth of those images being uploaded to your server. Now because we're doing this flow, if we want to resize the image or change the quality in any way, we're going to have to do it on the client side. So that's what we'll do. But whenever you generate this signed URL, you can add several constraints inside of it. So, we're going to assign constraints that say it must be of a specific file type. It must be under a specific size, and then that's what the client will use to upload the image. So,
even though we're doing this image transformation on the client, we're still at least restricting the size and the type. A bad actor technically could generate this URL and just upload junk data, but by limiting the size, we're we're limiting like incurring like any really big S3 bill. And one final piece to this flow after the client has uploaded that image to the S3 bucket via that signed URL is to then make a request to the API with the key to that uploaded image. And so that's step four here. We successfully upload to the S3 bucket. Then we can make a post request to our API and just say, hey, this is the key of the image that got uploaded.
And then we can store that key in our database so it's easy to retrieve if we need to like list images or whatever else. And whenever we do that, we can also validate on the server that this thing actually exists, right? So we're going to be storing metadata along with these images that have the user ID and then also some metadata about which location log they're associated with. So after the user uploads to the S3 bucket and then says, "Hey server, I've uploaded this thing. Let's store it in the database." The server can validate that metadata. It can say, "Are you the user that uploaded this image? Are you uploading it to the correct location log?" So because of all this metadata in the file that we're storing, we can do all of this validation here even though there's a couple of hops happening because technically the client could make any request they want to the server that says, "Hey, this file exists in the S3 bucket, but as long as we validate all of that metadata, we should be good to go." So this is the flow that we're going to implement. Let's get to it. Now we can work on uploading images. So as a user, I want to upload images to my travel log so that I can visually
select upload image
document my experiences. So, we should have a file input that allows for image selection, and we'll resize the images and optimize the quality. We'll create that pre-signed URL, upload to the pre-signed URL, insert that image key into the database, handle any errors along the way. So, first up, let's set up a link on the individual location log page that allows us to manage our images. So, I'm going to add that in the sidebar here. So, if we head to pages dashboard, this is where we're managing all the links. And we want to add a link when we're on the location log page. And right now we have view log edit log.
Let's add one more link to manage images. We'll call this manage images. And this will be link location log images. And we'll go to dashboard slug ID images. Pass in those. And we want to have just a photo as the icon. So I think photocog is one. If not, we'll update it. And we actually did have a bug earlier when we copy pasted these uh link items. These both have the exact same ID. So this should be link view location log. Okay. So now we actually need this page to exist. So in dashboard location slug ID, we will create a page called images. For now, we'll just have a template that says manage images. And here we can see we can click on it and then that loads the page. So that looks good. But we also need to make sure that all of the sidebar data is loading when we go directly to this page. And right
now it's not. So at the top of our dashboard, we are handling that here. So if we're on a current location log page, refresh that current location log. So we need to add the images page to this constant. So right here we'll add dashboard location slug ID images. And now if we go directly to this page, the sidebar populates appropriately. We can go back. Great. Now this is the page where I want to have the upload button.
So first let's increase the size of the title there. So we'll head to our images page. Let's just give this a class of text XL. Like so. That's much better. So now right below this I want to have an image upload button. So let's create a div. And if we check out the Daisy UI docs, they actually have this file input element. So let's use that. Put it here.
And then right below it, we'll have a button that says upload. Give us class of btn btn primary. And that looks like this. I want them to be on top of each other. So this div, I'll make a flexbox and give it a gap of two. Make it a flex column. So that's great. And then let's just give this a fixed width. So let's do a width of 72. That's great. I want to push this down a little bit. So, let's add some margin bottom under there to manage images. Let's do a margin bottom of two. That's looking great. And then right above this, I want to have an area where we'll preview the image that we're about to upload. So, let's create a div right above it. We're going to give it some fixed width and height so that way we can position the image inside of it. Uh, but we'll give it a gray background. So, let's do a bg gray of 500. And we'll give this a height of 30 and a width of full. And then inside of there, let's just display a message that says select an image. And we will center this. So let's make this text
center. We'll also make it text white because it's on a gray background. And then we'll make the container a flexbox. That puts everything in the center. So we'll do justify center and items center. And that looks like that. Now it's a little too big. So let's actually go with height of 28. Yeah, it's perfect. So now when I select an image, we want to preview it right here in this area. So let's add a script and then we'll have a state variable to keep track of the selected image here. So we'll just call this the image and this will be of type file or null. So it starts off as null and then we'll add a change listener to the file input here.
So whenever this changes, we'll call a function called select image and then that will update our image state variable. So this takes in the event. We'll then grab the file. So if we say event.target, that's going to be the input element. So we'll cast it to an HTML input element. And then that gives us access to the files. And we want to grab the first one because we're only going to allow uploading of one file at a time. Now we'll we'll make sure if that file was selected and exists, then we can update that image value to be that specific file. Now, in order to preview it, we need a URL for that file.
So let's create another state variable. Let's call it the preview URL. And this will be a ref that is either a string or null. Starts off as null. And then right after getting the file, we can set the preview image to be URL create object URL. So this lets us create a usable image URL. So we can use it in the DOM. We can pass in the file.
So now if the preview URL exists, let's show that instead of this select an image text. So here I'll say if there is not a preview URL show the text otherwise show this image whose source attribute is that preview URL we'll give it some alt text that just says upload preview and then we want it to take up the full height of the container. So let's give it a class that is height full and then we'll do object cover. So, if it extends outside the bounds of the parent, it'll just show most of the image. Okay, with that, now if I click browse, let's choose an image. And it shows up right there, ready to be uploaded. Let's add a little bit of padding in the container just so it pushes it down a bit. Let's add a P of one. So, now there should be a little bit of spacing in the preview. Great.
That's what I want to see. And now, just so we have some context because right now I I just realized we don't even know which log we're on. We're actually on the Tao live log. So, let's actually put that title up here that says manage Tao live images and we can get access to the current location log. So, if we head back here, we'll have some codes we can copy. We just want to grab the location log from the store and then we can display its name. So, here we will say manage and then inside of there location log.name. Uh, but if it doesn't exist, we'll say loading. And so now we have some context. Hey, we're on the Tao Live page. So I know that if I upload an image, I'm uploading it for Tao Live. I also think we could actually decrease the size of the title here. Let's get rid of text XL. See what that looks like. Yeah, I think I like that better.
Okay. So, so I can select the image. I see the preview. Uh, now let's make sure that the upload button isn't enabled unless we've actually selected an image. So on the button, let's just add the disabled prop. If image does not have a value. So if we haven't selected anything yet, it will be not clickable.
But if we select an image, now it will be uploadable. Great. So when we click upload, now we can initiate the flow that we talked about earlier. So right now we have our file input and before we initiate that flow, we do need to resize the image and optimize it. So let's create a function that gets called when we click this button. We'll say when this is clicked, upload the image. This will be async and first we will say if image does not have a value don't do anything. So if there's no image don't even try to upload. But if there is an image we want to resize it. So in order to resize it we need to know the original width and height so that way we have aspect ratio and also we know whether or not we we need to resize it.
resize / optimize image on client
So I want to have a max width of 1,000 pixels on any image that we upload. So we'll get the current width of this image and if it's less than a th00and then we won't resize it. We'll just optimize the quality. So in order to get the width and height we will actually just create a preview image and we'll use the image constructor built into the browser and then we can set its src to be that preview URL. And this is complaining because it could be null. So we can check for both of these. So if image doesn't have a value or preview URL doesn't have a value, then don't do anything. But it should because we're setting both of these at the same time.
But in order to get access to the width and height, we need to listen for the load event of this image here. So we'll add an event listener specifically listening for load. And when it has loaded, we'll get access to that width and height. So if I just console log out the preview image.width and preview image.ight, we should see the actual height of the image. So, if we select this and then click upload, we can see that the width of the original image is 4,000 pixels.
So, we definitely want to downsize this before uploading it. Now, in order to downsize it, we're just going to use a few functions built into the browser and then also use a canvas to optimize the quality. So, first up, let's get our new width. And the width will be the minimum value between 1,00 and the original width of the image. So, if the image was already less than 1,000 pixels, we'll just use the original width. But if not, like in this case, it's 4,000 pixels.
We're going to resize it down to 1,000 pixels. Then, we'll resize the image. And there is a built-in function in the browser that does return a promise. So, we'll make this an async function. It's called create image bit map. And you can pass in the original image. So, we're going to pass in that preview image. And then it has some options here for the resized width and also height. But if you just specify one either the height or the width, the other one will automatically have the correct ratio. So the resize width in this case will just be that width that's the minimum between a,000 and the original width. So this gives us a resized image. Now we want to optimize it and convert it to a JPEG. So the only thing we're going to allow uploaded to our S3 bucket are just JPEG images. So in order to convert it and optimize it, we'll actually draw this onto a canvas. So first we'll create a canvas. And because we're not displaying this canvas to the user, we'll actually use what's called an offscreen canvas.
Works pretty much the same way as a regular canvas, but it can be used like in web workers. It's kind of just like a behindthe-scenes canvas. And we can pass in a width and a height. So we want this canvas to be the exact size of the resized image. So we'll pass in that width. And then we'll pass in the height of the resized image. And this will be the height with the correct aspect ratio with the width that we resized it to. So now that we have the canvas, we can draw the resized image to it. So we will say canvas.get context. We specifically want the bitmap renderer. And then we can use this transfer from image bitmap function and pass in our resized image which is an image bit map. So this will draw that resized image onto the canvas and then the canvas has a method called convert to blob and this allows us to convert the file type to JPEG. So we can pass in
some options here. We'll specify the type we want image JPEG. And then another option we can specify is quality. So I'm going to set the quality to 0.9 or 90%. And that way it'll still be decent enough but it'll reduce the file sizes quite a bit for these images that we're uploading. Now, this returns a promise, so we'll await it. And now we have that resized image. So, at this point, we want to send some data to our API to actually create that pre-signed URL. And we're going to need a couple of things. We want the content size of this image that got resized. And built into blobs is this size property, and that's the size in bytes. So when we create the pre-signed URL, we can say that the image we're going to be uploading is of exactly this size. And so this will prevent someone from creating a pre-signed URL and then trying to upload something else to it. It'll have to be this exact size of the resize image. And then the other thing we'll do is we'll create a a checksum value. So a checksum
is a hash of this file and we can create the pre-signed URL saying the thing we're going to upload is going to have this hash. And then later on when we upload it, the S3 API will actually validate the thing that we're uploading to make sure it has the hash that we said it was going to have. So we need the size and the checksum. Now to get the checksum, we can also use some stuff that's built into the browser. So let's grab our checksum. We'll say await checksum. We'll create a function that takes in a blob and then creates a shaw 256 hash of the file as base 64 because that's what the S3 API accepts. So let's have another function here called get check sum takes in a blob which is of type blob. This will be an async method and then we'll do the work. First thing we need to do is get this blob as an array buffer. And there's a built-in method on blobs called array buffer. And so that'll give us back that array buffer. And then we'll create the shot 256 hash. This is going to give us back a buffer as well. So we'll call this the hash buffer. And there's another API
create image checksum on client
built into the browser called crypto. Under the subtle namespace is a method called digest. And here we can specify that we want to create the SHA 256 digest of this array buffer. Now we need to turn that into a string and B 64 encode that string. So we will do just that. We'll use B to A which is a built-in method in JavaScript that converts a string to B 64. And then we'll need to turn that hash buffer into a string. So we'll use string from char code. And then we'll create a uint array of this hash buffer and pass it in as arguments to from char code. So we're going to spread our new uint 8 array and then we'll pass in that hash buffer. So this gives us that shot 256 hash as a string and then we base 64 encode that string. So we have the checksum. We know the size because we resized it. So we have blob.size. Those are the two things we're going to send to the API to get back a pre-signed URL. So let's create
that endpoint that accepts those two values. Now if we head to the server, we're going to go into the API folder and then under locations slug, we'll create an endpoint called ID slash sign image. So we'll create a new folder called brackets id. And then inside of there, we'll create a file called sign image. And this is going to be a post endpoint. Now this will be an authenticated event handler. Essentially only logged in users can upload images and create these signed URLs. So we'll export default define authenticated event handler get access to the event and then first up we're going to do some validation. So we are going to be sending the content length and the check sum to the endpoint. So let's create a schema so we can validate those two things. So we'll have our image schema.
create pre-signed post url on server
We'll use Z from zod. This will be an object and the first thing we're going to have is the content length and this needs to be a number. But we can also validate that it's under a specific size. So before even creating the pre-signed URL, we can say, hey, it has to be a minimum of one byte. So it can't be an empty file. And we can also set a max size. And you can set this to whatever you want, but I'm going to set something really low so that way we don't run into any storage issues. I'm going to set it to 500 kilobyt. So let's create a constant called max content length. And we're going to do 1,024 * 1,024. So this is 1 megabyte. And I want I want to allow files that are half a megabyte or 500 kilobytes. So I'll just multiply that whole thing by 0.5. And so whenever someone attempts to create a signed URL, the content length cannot be more than 500 kilobytes. And then we're also going to take in that check sum value that is a string. Now let's
actually validate the incoming body. So we'll grab the result. This will be awaiting. So we'll make this an async function and then we'll say read validated body pass in the event and pass in image schema safe parse. Great.
Now if results success was not true then we'll return the error. So we can use our send zod utility function we defined a while back and we'll pass in result. And the event of course. So validate that they're sending us a valid content length and that they've given us a check sum which is a string. If it wasn't valid, send back an error. If it was valid, now we can try to create the pre-signed URL. But there's a few other things we need to validate, right? We need to make sure that first of all this slug exists because this endpoint is nested within that. Then we need to make sure that the location log with that ID exists. And we need to make sure that this specific user owns that location log before we create the pre-signed URL because this pre-signed URL is going to be tied to this specific location log.
Now, if we look at the get method for a location log, it basically has all of that logic, right? It validates the slug, make sure that a location exists, make sure that ID is a number, make sure that this user actually owns that location log, and then if it does, it returns it. So instead of just copy pasting this logic, one of the nice things about these API endpoints is that they can call each other. And so right here I'm just going to directly call that endpoint because it does all of that validation and if it throws an exception, it'll return the correct error. So if we await the call to fetch that specific endpoint and then we can specify the URL as API locations slug, we'll grab the slug from the route params and we'll also grab the ID from the route params. And that can be done like so. So we'll copy this, grab the slug, grab the ID, and this will actually just call the API endpoint internally. So it looks like a fetch call, but what's nice about Nux is it's
smart enough to see this on the server side and be like, "Oh, this exists internally." And so it will literally just invoke this function directly. It's not actually doing like a roundabout API request. Now, because we're making this request on the server side, it needs to be made in the same context of the user that was making the original request because the request that was made by the user includes their authentication cookie and that actually lets us know if they own a specific location log and can they access it. So, in order to make this request in the context of the user, we can actually say event.d dollar sign fetch and this makes sure that all of the incoming request headers also are included when we make that internal request. So this is pretty much all we need that call will go over here do all of this validation. If any of the validation fails it will literally throw that error and send it back. But if all of that is successful then that means the log exists and it's owned by this user. So they should be allowed to
upload an image for that specific log. So if we make it past here, we're ready to start creating that signed URL. Now to do this, there are two packages we can install. The first one is the AWS SDK S3 client. So this is a client library that lets us make requests to the S3 API. And then there's another package called AWS SDK S3 pre-signed post. And that's just a utility function that allows us to create that pre-signed post request URL using the S3 client. So let's install those libraries. We want at AWS SDKclient S3 and at AWS SDKs S3 pre-signed post. Now even though we're talking to minio locally, we can use the AWS client. And that's the beauty of S3 compatibility because any API that has S3 compatibility, we can use this client here. So when we're in production, we'll potentially have a Cloudflare R2 bucket and this client will work with that as well. We'll just need to make sure we specify all the correct settings and
URLs. But the client will work for any S3 compatible API we pointed at. So now that we have those, let's import our S3 client. And this comes from AWS SDK client S3. So we'll create an instance of the client here. Then we can pass in all of our options. First up, we specify the region and we'll pull this value in from our environment variables. So a little bit ago, we updated our type safe env to include all of these values. So we're just going to pass these values in. So that way when we're in production, we can have our production values. When we're running locally, we have our local values. Of course, that's how ENVs work. So this should pull in our env. And we want the S3 region like that. We also want the S3 endpoint. So we'll do ENV. S3 endpoint. And then we can specify our credentials. And so this takes in the access key ID. So this will be env. S3 access key. And then it also accepts the secret access key and this
will be env s3 access secret. So this creates our S3 client that's ready to talk to this specific S3 API. And now we can use everything we have to create the pre-signed post. Now when we're putting a file into an S3 bucket, it has a key. And the key is essentially just the file path inside of that bucket. So we're going to create a variable that is the key. And the way that we're going to store these is every user will have their own folder in the images bucket that and that folder will be the user's ID. So we're going to create a file path that represents that. So first we start off with the user's ID and because we know the user is already authenticated, we can grab that from event.context user. ID. Then we'll put that in a folder that is for this specific log.
And we already know what that ID is because it's in the params. So we'll specify that ID there. And then finally, we need the file name. Now, for this, I'm actually going to just create a global unique identifier or a grid. So that way, each file that gets uploaded has a unique name. So we'll grab the file name. And here we'll just say crypto.random UYU ID. So this gives us a random UU ID. That'll be the file name.
So we'll specify that there. And then we know that only JPEG images are allowed to be stored here. So we can just assume that the file extension is JPEG. So this is the key. This is where we're going to be storing it inside of our images bucket. Now we can create that pre-signed post. So we'll import create pre-signed post and this comes from the AWS SDK S3 presigned post and we'll call it right here. So this gives us back a result. It returns a promise. So we'll await it. We pass in our client instance and then we can specify all of our options. So first of all, we specify what bucket do we want to store it into.
And this also is in our environment variable. So we'll grab our S3 bucket. And then we specify the key. And we just created that variable. So that will be that. And then we can set an expiration. So we talked about this earlier. Essentially, this URL that gets generated can be used to upload to the S3 bucket. And we don't want it to be usable forever. Essentially, it's kind of like a oneanddone thing. Once a file has been uploaded with that pre-signed URL, it shouldn't be used anymore. But there is potentially like network latency in terms of creating this URL and then uploading the image. So you want to give this expiration enough time that the client is going to have time to actually upload the image. So I'm going to set this to 120 seconds or 2 minutes.
I've seen some apps that have like an even lower value, but again you could run into latency issues where by the time the user uploads the image, it's already expired. So I think 2 minutes is perfectly fine. And we also have lots of other checks and balances I'm about to show you that make sure that this pre-signed URL is specifically used by this user for this image with this checksum and this content size. So I think an expiration of 2 minutes is perfectly fine. From there we'll specify some fields. This is where we can pass in the checksum value. So we're basically saying create this pre-signed post URL and expect that later on when a file is uploaded the checksum should match the checksum that we're passing in here. Now this field is called x amzum-sha 256 and the value we want it to be came in the body here. So we can say result.data.cheum. And then from there there are a few other conditions we can specify. Essentially, we can lock this
down further. So, the first one is to specify the content length range. And because this is a range, you could technically say, okay, the length of the file that's going to be uploaded is anywhere between zero and a,000, something like this. And so, that would limit your uploads to being up to a,000 bytes, but we know exactly the size of the image that they plan on uploading because we passed it in in the URL. So, we can actually say the minimum size is result.data.contentlength content length and the maximum size is result.data.contentlength. So this says the image that gets uploaded must exactly have this content length. So we're adding all these checks, right? It has to be this exact size. It has to match this check sum. Then to lock it down even further, we can actually include some metadata here that is the user ID and then also the location log ID. So here we'll add an equals condition and we'll specify a field. We want the x-z meta. So anything that's dash meta
will be accessible when you get the object information from the bucket. So you could attach a bunch of extra properties here. But we're going to attach the user ID and the value is the current user's ID. So event.context do user id. Now all of these need to be strings. So we will tworing that ID because it is a number. And then similarly we can attach the location log id. So this image is specifically associated with this location log ID which is the ID that was in the URL because we already validated they have access to this. We put that in the metadata and we'll be able to pull that out later. Okay, so this is looking good. I realize I called this variable result and we already have a variable called result but that's okay because we're going to dstructure this because this gives us back the URL. This will be the URL that the client can make that post request to. And then it also gives us back the fields. These are the fields that need to be included when the client makes that post request. So the thing that we'll give back to the client is
the URL, the fields, and we'll also let them know the key. So they'll know where is this file eventually being uploaded to so that they can link to it. Now, one last thing is we're going to attach the user ID and the location log ID to these fields. So on the fields we can just add a property for X amza user ID and on this don't include the dollar sign that the dollar sign is only included on conditions if we're setting the property on the fields no dollar sign and then set it to be this user's ID and then we'll do the same thing for the location log ID. So we'll specify in the fields X Amazon metallocation log ID and that's going to be equal to the ID. Now, technically, we could just set these two fields on the front end because, like I said, the front end's going to get access to these fields. It's going to include those in a post request to this URL and it could populate those itself because it already knows who the user is and who we're creating this location log ID for. So, this is kind of just a convenience. So, that way on the front
end, I don't have to change anything. I get back this data and then I can immediately make a post request here and include all of those fields. So with that when I hit this endpoint we do all the validation we create the pre-signed post and then send it back to the client. So let's head back to the front end and call this endpoint. So for this let's first set up a loading variable.
get pre-signed post url on client
We'll just call it loading. It'll be a ref that starts off as false. And then once all of this stuff starts happening we'll set loading.value to true. So this processing of the image and everything else even before we create that pre-signed URL that could take a little bit of time. So we set loading to true here. And then finally, when we're ready, this is where we'll make that request. And for this, we will need the curf fetch function. So let's pull that in like so. And then right here, we can make that post request. So we're going to get back the result. We'll await the call to cesur fetch. This is going to be to slash ai/los slug. So we'll make this a template string. And we need access to the current route. So let's grab that as well. Like so. And then the URL will have route.params.slug slash route.paramsid slash sign image. Now
this is going to be a post request and the body is going to have two things, right? It's going to have that check sum and it's also going to have the content length and that will be blob size. Awesome. So we resize the image, optimize it, we call the endpoint, it does all the validation, it then creates the signed URL and then we get it back. So let's take a look at this result and if this is successful then we can finally actually upload the image to that pre-signed URL. So before we call it, let's actually show some loading state. And we'll also disable the button in the input. And so if there is no image or we are loading, disable the button. And then we'll also disable the input if we're currently uploading.
So if loading is true, disable the input. And then let's show a loading spinner on top of the image while the upload is happening. So right here, I'm going to have a div that is only visible if loading is true. I want it to take up the full height and width. So we'll just say size full. And I'm going to make this absolutely positioned. So we'll make it absolute. We'll make the parent relative so that the absolute positioning will work. So we'll set position relative on it. And then we'll make it a flex box with a loading spinner in the center. So we'll say flex justify center items center. Let's also give it a background of black with some opacity. So the image will be behind this div but you can see through it. And then on the div itself we'll have a loading spinner. We'll give this a class of loading. Loading large. Okay. Moment of truth. We'll head back to the app.
Select our image. Click upload. It's it's loading. It's loading. And the endpoint was not found. So this sent a request to API location Denver for sign image. Let me make sure I specified that right. So API locations. Um so let's actually display the error if one happened because that's a definite possibility. So let's actually wrap this in a try catch. Move this in here. Get access to E and then let's say if E is an instance of a fetch error and then we'll import fetch error from fetch. So if it's a fetch error then let's set an error message on the component. So we'll have another state variable. We'll call this error message.
Initialize it as the empty string. And then if it was a fetch error, we can set the value to be E as fetch error dot status message. And if that doesn't exist, we'll just set it to unknown error. And otherwise, if E is an instance of error, which it should be, then we're going to set the message to be E as an error dossage. So that'll just be the top level message. And then finally, if none of that is true, we'll set it to unknown error. Okay. Now, we want to display the error message. I think I'll just display it right on top of the image. So, let's actually say um if we're loading or error message has a value, display this div on top. And then if loading is true, display the loading spinner. And then otherwise if the error message has a value then we'll display the error message right here and we'll give this a class of error. Okay. So if something goes wrong it'll just display
that error message right on top. And then if they resubmit the form let's clear out the error message. So right here we'll say error message.value is nothing. And then of course once all of this is done we will set loading to false. Okay let's give it a try. A hard refresh. try to upload an image. It fails and then it says not found. Great.
Okay, so that's decent. Let's actually send the request to the correct URL API locations. And now hopefully we'll get back a signed URL. So we're going to upload that. There we go. So the API returns all of the fields that need to be included in the post request, including the key and all of our meta and then the actual URL that we need to make that post request against. So we're right now running locally. We're talking to min.io. So the endpoint we need to hit is here. Now you can see that it actually says images.lohost. When we're running with minio, we don't have really a way to set up subdomains locally. So let's actually add some configurations so that the client knows to not have the subdomain here. It should actually be on the end as a as a path. So if we head back to our API right here, when we create the S3 client, there's an option called force path style. And we want to force the path style if we're running on local host because if we're in production then the subdomain will be the bucket name
but when we're running locally it's not. So we'll say if env. S3 endpoint includes localhost then force the path style. Otherwise when we're running in production it'll include it as a subdomain. So with that setting, now when we create this pre-signed post URL, the URL we're going to make the post request to is localhost9000/ images. Great. And then these are all the fields that we can specify. Awesome. So now let's do just that. So back on the client right here, this result gives us access to the fields, the key, and then also the URL.
upload image to s3 from client
So now we want to make a post request against that URL with these fields. So right here we can use just dollar sign fetch because this is actually making a request to S3. It's not internal to our app. We want to make that to that specific URL. The method is going to be post and then our body is going to be some form data that has all of these fields. So let's create some form data.
Now fields is just an object with keys and values. So essentially we'll iterate over that and then append each of those to the form data. So let's say object.ent entries with the fields for each one. We're going to grab the key and the value and then we will append it to the form data. So we'll say form data.append key and value and we know that all of the values are strings. So we can actually just cast this to a string and spell value. Right? So this will construct our form data. This is what we then will send as the body of this request. And of course we need to actually upload the file as well. So before we send it, we'll say form data.append and we can append the file here that is that resized blob that we created right there. So this is what's going to actually upload the image to this signed URL. Now one last thing is we need to include the header that says validate the Shaw 256 hash. So here
under headers, the header we want is x amzum-algorithm and we'll set this to sha 256. And so now when the S3 endpoint receives this blob, it's going to generate the checksum on the S3 API server and then it's going to validate that checksum against the checksum we used to create the pre-signed URL. If it's valid, it'll allow the upload to happen and we should be good to go. So, if this was successful, I'm actually just going to log out a URL that is the image that got uploaded. And it should be at the URL, which is our S3 endpoint/ images. And then we want the specific path to that image. So, that'll just be slash and then the key that we got back from the endpoint above. And if everything was successful, this should be the actual URL to where that image is hosted in our S3 bucket. So, let's give it a try. We'll select our image. We'll
click upload. It was successful. We have a URL. If we visit it, there it is. That's that's Tao. I saw them live. And so the image actually got uploaded. And if we head back to our minio dashboard, we can actually look in our object browser. We can head into the images bucket. We see there's a folder for user with ID 4. There's a folder for the location log ID with four. And then there's the image that actually got uploaded. And if we look at it in the minio dashboard, we should actually see some of the meta data as well. Yeah, you can see here are the two attached properties, the location log ID and the meta user ID. So we'll always have access to these to know that this one image is associated with that user and that specific log. Great. So the image is uploaded. Now we need to actually add it to our own database. Right? That's the final step. Essentially it's in the bucket. Now, we should add it to our database so we know that this specific key is associated with this log and we can actually list out those images whenever we're on the the view log page.
insert image metadata into db
So, let's do just that. So, we'll create an API endpoint that actually inserts into our location log image table. So this was a long time ago, but if you remember when we set up our tables, we have the location table, which is all the places we visited, location log, which is each time we visited. We also have the location log image table. And this stores the keys of each of the images associated with a specific location log. So we'll create an endpoint where we'll actually insert into this table the key of the image that just got uploaded. So if we head to our server folder, I want an endpoint which is API locations slug id image and we'll make a post request against / image and that will allow us to add the image to the database. So we'll call this image.post.ts. We'll start out with our authenticated event handler. Get access to the event. We'll make this an async method and the body of this request will include the key. We'll get the user ID
from the event context and we'll get the location log ID from the URL. But we will be validating that key property. So if we head to our DB schema, we can create a zod validator. So here we will say export insert location log image and this will be create insert schema. We'll pull that in from drizzle zod. We'll pass in our table definition and then we're going to omit everything except for the key because the dates are automatically added. We're going to add the user ID and the location log ID when we insert it. Really, we just want to validate that the key is valid. So, first let's omit everything except the key like so. And then we can specify a custom validator for the key. So, this gets access to the field. And then I'm going to specify a regular expression that validates that path, right? because the path is user ID/log ID slash a uyu ID.jpeg. So I'm going to make sure that
the key follows that pattern. And for this I'm going to use a regular expression. Now I haven't used AI during the entire building of this app in this video but this is a perfect use case for AI. I actually generated this reax with AI. But what this says is the key should start with one or more digit followed by a slash. So this is going to be the user ID followed by one or more digits. So this is going to be the location log ID followed by a slash followed by a UYU ID. And so a UI ID is essentially 8 characters 12 characters. And it always has that format. So this is going to make sure that the key actually is a UYU ID. And you saw in our backend code, it always ends with JPEG. And so this regular expression makes sure that the key that we're inserting matches the pattern for the keys that we're setting in our S3 bucket. And then if it doesn't match that pattern, the error message will be invalid key. So this is our
validator. Let's also export a type for this insert location log image. And we'll use Z.infer. We'll import Z from zod. And we'll infer the type of this schema, the insert location log image schema. Okay. Now that we have the schema, we can use it to validate the incoming body. So right here, we'll grab the result. This will be await read validated body. Pass in the event. We want that insert location log image dots safe parse. So that will validate the key. If the key was not valid, we're going to send back that error. We'll pull in send zod error and pass in result. And the event. So that validates it. But if it was valid, now we're going to try inserting it into the database.
Now just like we had the validation earlier where we made sure does the location with this slug exists. Does the user own this specific location log all of that logic is handled in getting a location log by slug and ID. So we'll replicate that here. Exactly. Essentially we'll pull in the slug and the ID. We'll make that request right here. If this fails then they're trying to insert a location log image for something they don't own or that doesn't exist. But if this is successful, we can start to actually insert it into the DB.
Now, we could just directly put this into our database. But one bit of validation we could do is actually query our S3 bucket and make sure that this key actually exists, right? So, we we're grabbing the key from the body here. And we also know what the user ID is and what the location log ID is. So, we can look for a file that has the specific key. we can pull its metadata, make sure that the location log ID is this, and make sure the user ID is the current loggedin user's ID. And if all of that is true, then we'll actually insert it into the database because if any of that doesn't match, then something went wrong, right? They're trying to add an image that they don't own or somebody is just messing with this endpoint and sending us random data. So before putting it into the database, let's make sure that it actually exists in the S3 bucket. Now, for this, we'll need an S3 client as well. So, I'm actually going to extract out this bit of codes here that creates the S3 client. So, that way we can reuse it in multiple spots. So, I'm going to copy this in our utils
folder. Let's create a new file called create S3 client ts export a default function and then just return this. We'll import this from all the spots like so. And then let's use this function in our sign image endpoint. So here our client is create S3 client import it in. So now that's nice and reusable and we can create that same client right here and we'll import it in. Now that we have the client, we can attempt to get that specific object from the bucket. So built into the AWS S3 SDK is a constructor called the get object command. So we'll import that in and we're going to create an instance of this command like so. And this takes in two options. The first one is the bucket. So which bucket are you requesting it from? So we'll import our env. And then we want to grab the name of that S3 bucket. And then we're looking specifically for the item that has the key that was passed in in the body. So if we say result
data.key, this is the key that we're looking for. Now I want to actually query the client to say, hey, does this object exist? So this is going to give us back the response. We'll say client.end. And we can pass in that get object command. And now we can actually look at the metadata. So response metadata has all of those meta properties that we added onto it. And by default, it's just a record string string. So let's just create like a a useful type so we get some good type completion. So we'll have a type here called the object metadata. And we know that it has two things. It should have the location log ID, which is a string.
And it should also have the user ID, which is a string. So right here we'll grab that metadata and say response metadata as object metadata. But it's possible that somehow an object made it into our bucket without any metadata. So let's also say that hey this could be undefined as well. Then if there was no metadata meaning somehow it got uploaded without it or the metadata.loation uh location log ID does not equal the ID for the one we're trying to insert or the metadata user ID does not equal this specific user's ID. So we'll grab event.context do user id and we'll tworing it. So if any of these are true then that means we do not want to put this into our database. So we're just going to send back an error. So let's return send error for this event. We'll create the error. the status code will just be let's say 404 because we didn't
find the image in the bucket. So our status message will be image not found. But if that object with that key does exist in the S3 bucket and all of the metadata matches, then we'll insert it into our database. So we'll say the inserted location log image will be a call to our queries file. So we're going to create a new query for insert location log image. We'll pass in the location log ID, convert it to a number.
We'll pass in result.data, which has the key, and we'll pass in this user's ID. So, this is event.context user. ID. And finally, we'll return the inserted value. So, let's go create this query called insert location log image. We head to our DB and queries folder. I'll create a new file for location log image. And we'll export a function called insert location log image.
accepts the location log id which is a number. Accepts the insertable which is an insert location log image and it accepts the user ID which is a number. We'll then do the business. So the inserted value will be a call to our DB.
We're going to await it. We'll make this an async function. We'll say DB, we'll import it in. We want to insert into the location log image table. We'll import that in from the schema. and we want to insert the values. We'll spread the insertable. We'll specify the user ID and also the location log ID. We'll then return what was inserted and return it from the function. Awesome. So, this puts it in the database. This validates that the incoming body is valid, that all of this stuff exists, that it actually exists in the S3 bucket, and then we insert it into the DB. So, let's import that function. And now let's actually call this endpoint from our client side. So right here after making the request to AWS to actually upload it, we'll await that. When that's done, now we can try and insert it into the database. So this will be a curf fetch.
It's going to be a post request to slashimage and the body of the request is just going to include the key. This will give us back the inserted image and we'll log it out. All right, moment of truth. Um, first up, let's actually delete any of the images that are in our S3 bucket here because they they got inserted into the bucket, but they didn't get put into the database. So, let's delete this and then we'll re-upload it because it will then in turn be inserted into the database. So, let's choose our image upload. And it was successful. If you look at it, it has the key, it has our created at. So, this was actually put into the database.
Fantastic. So, let's look back at our checklist. We've done a lot. We've done a whole lot. So, the images are resized. The quality is optimized. We have our loading spinner. We're creating the pre-signed URL. We upload the image to the pre-signed URL. We add it to the database. We display any error messages. Now, we need to actually say, hey, the thing got uploaded and we need to show the image on the page. An easy one before we do that is let's show an icon on that upload button. So, if we head to icons for photo, this is a nice photo upload icon. Let's add that to our upload button. So right here, let's add our icon. The name is that size is 24.
list images
And that looks great. That's a nice upload button. So in order to display these images, I actually want to include the images whenever we request the location log itself. Because if we do that, then it's just a matter of calling refresh the current location log. And if we're including all of the images, any of the most recently inserted images will be included along with that updated data. So let's update our tables to have those relations to say that one location log can have many location log images.
After we've set up the relations, we can update our endpoint to include those related images whenever we retrieve a specific location log. So to the database. Now the way we set up this relationship is going to be very similar to how we set up the relationship between location and location logs. So for location, we set up the mini relationship. So we're going to also want a mini relationship for images on the location log. So on location log, we can say that the images is mini location log image and we'll import that schema and then we can dstructure many from here. So when we query for a location log, we can include the list of every associated image. Then on location log image, we need to add the relations as well. So we'll specify these here. We'll call these the location log image relations. We'll import relations from Drizzle. We're defining relations for the location log image and we are saying
that it has one location log. So we'll specify the location log table and we'll say that the location log image dot location log ID relates to location log ID. And then we don't need to import many anymore. So now with these relations set up on both sides, when we query for a single location log, we should include the images. So when we find a location log, we'll say with images and it's just autocompleting as image. I I want this to be images. So let's double check how we set that up.
So in a location log, yeah, this should be images because it has many images. And then over here, we can call it images. The other thing is we can sort these by most recently uploaded. So let's actually include an order by clause in here as well. So we'll say orderby and we want operators.cending and we want descending created at date. So we'll say fields.created at. So the most recently uploaded images will always appear at the front. Okay. Now in our front end we should update the type to also say that we have the images here. If you remember back when we did this for location, we actually set up this helper type here that said a location with logs and then we added the type on there. We want to do a very similar thing for a location log. I want to export a type that is select location log with images. And so this will be select location log, but it will be a composite type where images are of type select location log image.
And then we'll have to define this type. So over in location log image, we'll also create a type called select location log image. And for this we can just infer the select type from our table here. So we should be able to say type of location log image which is the table schema infer select. So this gives us back a type that specifically is what do you get when you select for that element. So that's great. And then over here we'll be sure to import that type.
And this should be an array of select location log image. Okay. So now that we have this usable type, let's actually update the type on our front end to use this so it knows that it has access to those images when they are loaded in. So if we head to our store or locations, when we set things up for select location log, we should actually use the type select location log with images.
And so now we'll get access to those images on the front end. Import that instead. So, if we head to the images page, before we list things out, let's just display a status message right here. So, we'll just have a div. We'll say there are and let's say the location log images.length. So, we should get access to that. We'll say images. So, here we're going to display how many images there are. So, as we upload each one, that number should increase. And what we can do is after successfully inserting a new image, we'll just refresh the current location log, which will request uploaded image should appear inside of there. So right after this, we'll say await location store.refresh current location log. And then we don't need to hold on to this result anymore. And just like that, we can see there are one images. So let me let me put that message off to the right just for a second. So let's actually create a container here that just flexes
everything as a row. So we'll make it a flexbox. And now the image appears off to the right. This is just temporary because I want to show you that this is working. So if we try uploading a second image, we upload it, it refreshes. And now we have access to all of those images on the client side as well. So before we actually show the images on the page, let's actually clear out the state of this form so it's ready to upload new images. So when a upload was successful right here, let's reset all of our values. So let's set image back to null. Let's set that preview URL back to null. And then if we actually want to clear out what's selected here, we need a reference to that input element. So let's create a ref. Let's call this the image input. We'll create our template ref here. So we'll say use template ref.
Specify the image input. And then now when we clear everything out right here we can say image input do value. So value gives us the actual element itself and then we want to clear out the value. So we're just going to set it to the empty string. Now we can't use optional chaining like this. So let's just say if we have a reference to the image input which we should then reset the value to empty. And just like that we should have a form that resets. Let's test this out on another one. Let's do me first in the gimme gimmies. Going to upload an image.
So, right now there are zero images. Upload an image. Upload. It resets. And we're ready to upload another one. Great. Now, let's actually list out these images. So, for this, I just want some cards that have the image inside of it. And the cards will have a fixed width and height just like we have for the location cards. Like on this, the cards are basically going to look like this, but it'll have the image preview inside of it. So let's set it up on this page first because I want it to appear here and then we'll just reuse that component on this page over here. So on the view page, we should be able to iterate over those images. So if we head to the page for this specific location log, right below the description, we want to show a list of uh images. Let's create a container for all the images.
Let's make this a flexbox. Give it some margin on top so it's pushed a little bit below the description. Give it a gap of two and then we'll do overflow auto. So if there are multiple images, they'll just scroll. Then inside of there, we want a card for each of the images. So I'm going to repeat over each image in location log images. We'll give it a key, which is just going to be imageid.
And then we'll give this some classes. So I'm going to make this a compact card. And I'm going to give it a fixed width and height. So we'll make it a height of 40 and a width of 64. I'll give it shrink zero so that way it doesn't shrink whenever we're changing the size of the flex container. And then the card itself will be a flexbox to center everything inside of it. So I'll set this to a flex. We'll do item center and justify center. Now inside the card we want to display that image. So we'll create our image element. We'll bind the source here to be the full URL of the image. Now the base URL is our S3 endpoint. I'm going to hardcode it right now, but we should pull this in from our environment variables. Right now, we can't exactly do that because this code is running on the client side, but for now, let's just hardcode it as http/lohostport 9000 / images slash this specific key. So, we can grab image.key.
Now, I want this image to be in the card body. So, we'll create a div, put that inside of there. Give this a class of card body. And then we'll make the card body take up the full height and width. So we'll give this a size of full. And then we'll make the image take up the full height and width of its parent. But we'll also do object cover just in case there's any overflow. It just fills up the card. And just like that, we can see the images. Nice. Let's also give a background color to the cards so they're a bit more distinct. So each of these should have a BG base of 300. Yes, that's what I want to see. So now uh when we're on any specific page, we can list out those images. So we go here, we can see the images. Fantastic. I uploaded some Blink182 images when you weren't looking. So there's that. Sweet.
So the images are listed out. Let's extract this into a component. So that way we can also show the images on the manage images page. And eventually this is the page where we'll delete images if we need to. So let's extract this out. I'm going to call this the image list. So in our components folder, let's create a new file called image list.
Create our template, throw this in here, and we just need to accept a prop, which is a list of images. So have our script. We'll define our props. We're specifically looking for images, which is an array of select location log image, like so. And then we'll just repeat over the images. Okay. Now, let's use this component. This is the image list. So right here, I want an image list. And the images are location log images like so. But now that we have that, we can reuse it on the image management page. So instead of displaying there are X images, we can display that image list here. And on this page, we should get access to the current location log. And we have it.
But it's possible that this is undefined. So we'll do this. If it doesn't exist, pass down an empty array. So now on the manage images page, we see those listed out here. Let's add some margin to the left. Do a margin left of two. So it has some nice separation. But now if we upload a new image. So let's actually head to Blink182. I have some more images for this. If we upload a new image, that should load and then instantly appear because we refresh the location log. And I can upload more, too. Let's upload this one. Go. Nice.
Okay. If we check back in, we have success feedback. The images appear after being uploaded. And we do have that icon now. So, we've done it. We can upload images for each of our logs. This is great. We are so close. So close. So, one thing is we we actually skipped on this earlier is we should show some empty state on the main page if we don't have any images. That just says something like add images to get started. So, let's do that on the specific location page. if the list of images is empty. So have a div and if images.length is empty. Let's display a message. And I want this to look very similar to on the main dashboard when we had the thing that said add a location to get started. So if we head there, that looks like this. I'm going to copy it. We're going to use this instead. And actually, we won't even have help text.
We'll just literally say add image. And then the icon should match the one that we have in the sidebar. So this should be the photo cog. And this is going to go to the page which is dashboard location slug ID images and then the params are the slug which is the current route.params.lug and the current ID which is route.paramsid. So if we don't have any images, we have this link takes us to this page and we can add an image like so. All right, last piece. We actually need to have the S3 URL available on the client side because right now we've just hard hardcoded localhost 9000. So when we deploy to production, we want this to be our actual S3 production endpoint. So the way that we do that is by specifying our runtime env. So inside of our nux
config, there is an option here for runtime config. And inside of here, we can specify any variables that we want to have access to on the client side. Because by default, all of our environment variables that we've specified in here are not accessible on the client side. None of these can be even touched if we're in client side code. They only can be used in server side code. But specifically the S3 endpoint that's not any secret that is something that we can expose to the client side. So that's what we're going to do. So back in the Nux config. So in here we can specify what we want access to. And here I'm actually going to define a new environment variable. I'll call this the bucket URL. So let's call this S3 bucket URL because this is going to differ depending on if we're in production or if we're in development.
So, back in our env file, we'll make sure we have access to this as a string. And then in our env, the S3 bucket URL is going to be a combination of the S3 endpoint and the S3 bucket name because it'll be localhost 9000/im images, but when we're running in production, it'll be images AWS whatever else. So, we'll have this as an extra environment variable.
So right here our bucket URL is localhost9000 / images. Now that we have this specified here and we're exposing it to the public, we can access it inside of our image component. So now in this component, we can get access to the runtime config. So there's a hook called use runtime config. Store that in a variable called config. And then right here, we'll specify we want config.public. S3bucket URL. And now when we're running in production, this will be nice and configurable. But if we head back to our app, do a refresh, images are loading in just fine, and we're ready to deploy this and and use all of those environment variables in production as well. So at this point, we're done with all of this. We still need to deploy. So next up, we're going to set up our S3 bucket in production.
Make sure all of our environment variables are specified in the right way, and then make sure that we can upload images when we're running in production as well. Now, I'm going to create an S3 bucket inside of Amazon so that we can actually upload these images when we're in production. Now, I did say you could use any S3 compatible API, but we're doing something that actually isn't supported by a few of them. So, I looked into Cloudflare R2 and also a service called Back Blaze, and they currently do not support pre-signed post URLs, which is how we're generating our pre-signed URLs. There's another way to generate pre-signed URLs called pre-signed put that is supported by Cloudflare R2 and Back Blaze and a lot of these other services, but the pre-signed post allows us to set that content length condition. And I want that feature so that users can't just upload images of any size. So, if you want to use R2 or any of these other services, you might have to switch to
s3 production setup
pre-signed put URLs. And the code for that is fairly similar. It's just you'll be making a put request instead of a post request and you can't specify some of the same conditions. But we are going to be using Amazon S3. So let's get started. Let's search up here for S3 and we will create a bucket. So right now my region is US East 2. I want to create my things in US West one in California.
It's closer to where I am. Typically you would create this closer to where your users are. You might actually have multiple buckets so that you can store images close to wherever your users are uploading them. I'm going to create my bucket here in California. So, we'll create a bucket. I'm going to give it a name. We're going to call it next travel log images. And then we are going to need some level of public access. So, we'll uncheck this. Acknowledge. And we're still going to have to set up a specific public access rule, but this just lets AWS know that, hey, I I want to do this. All the other settings can be left the same. And then we'll create the bucket. Now here under permissions is where we can enable public read access. So here under bucket policy click on edit and then let's look at the policy examples and we can find an example of public read and this linked me here. I'll copy this example policy and then we'll update it accordingly. So we aren't specifying a specific tag on an object. We just want to allow get
object for anything that is in that specific bucket. So this will allow anyone to get a file from the bucket if they know the key to that specific file. So let's save that. And then we also need to set up the corores policy. So if you scroll all the way down to the bottom, you can set up corores here. So if you click on edit, this is how you'll configure it. And for allowed origins, you'll want to specify your actual percentell or whatever your production URL is. If you want to be able to upload from local host, you can add that as an origin as well. So if you do this, this would also allow you to upload images when you're running in dev. Now for my app, we're only uploading to this bucket when we're in prod. So these are the settings that I want. If you click on learn more, they have this section and if you go into using the S3 console, there's another link that talks about the elements of a course configuration.
And this has some examples that you can pull from, but these are the settings that worked for me. Now we need to create that access key and secret. So if you click up here and then go to security credentials, we can create an access key. So for this, I'm going to be creating a root access key. This is this account is only associated with this bucket that I'm working on right now.
Typically, you want to lock things down a bit further. So you can actually create separate users, create roles, and then create access keys that are specific to that. I'm okay with creating a root access key. If you want to be more secure, you can look more into how to do all those things with AWS. So, I'm just going to create this root access key. You should then copy the two values that it gave you, and that's what you're going to set in the Versell dashboard for your AWS key ID and secret. Now, to get our S3 endpoint URL, let's actually just upload a file directly from the dashboard here. And after that, we'll get exactly what URLs we need. So, I uploaded this image. If we select it and then say copy URL, this will show you the URLs we'll need to set in our environment variables. So this URL here without the file path will be the S3 bucket URL environment variable. And then the S3 endpoint environment variable is going to be this URL without the bucket name. So it'll just be this
URL. So here in the Verscell dashboard, I've set all of these. You'll see I have the S3 endpoint. That's the URL without the bucket name. The bucket URL is the URL with the bucket name at the beginning and then we specify the name of the bucket and also our region. So the environment variables are set in Verscell. Now if we head over to GitHub, our environments, we need our build environment. We're going to add all of these values here. Specifically for GitHub, I'm just going to set them equal to all of the values I have when I'm running in dev because those values aren't actually used in our GitHub actions. If we were actually trying to upload images in tests or something like that, I would need to specify a real endpoint and real access key. But for now, they just need to exist so that the llinter can run. So I'll add all these here in GitHub. And then when we're done with this, I'll update our YAML file to pull in those environment variables as well. So those were all added on GitHub.
Now in our GitHub workflow file, we need to expose all of those as well. So I'm going to specify all of these and pull them in from our secrets like so. Now with all of this, whenever I merge this in and deploy it, we should be connected to our production R2 instance when we're running our app on Verscell. Now let's test this working in production. As you can see, I already uploaded an image, but let me show you what to look for. So if we upload an image, let's take a look at the network tab and then click upload. We should see that post request to our server which creates the signed URL and responds with it. But you can see that it's actually responding with our S3 URL that we will then make that post request against. So right after that we see the post request that goes to Amazon that includes all of the fields including our attached image. You can see the binary data there. And then finally, because we got back a
successful response, it then makes a post request to our server that actually adds the image to this specific travel log. Now, there's a few things that could go wrong. I would say the main one is getting like an access denied error, and that typically happens because this post request doesn't have the correct cores headers. So, we added that core setting inside of the S3 console. Make sure that has the proper origin, otherwise your client will not be able to make the post request against this endpoint. So, we're running in production. We can move on to the next thing. Next up, as a traveler, I want to delete images from my travel logs. So, we allow the users to add the images.
delete images
Now, we should allow them to delete. And when we do this, we want to make sure that first we remove it from the database, but we should also remove it from the S3 bucket. Now, for this, we'll do it on the manage images page. So, if we head into a travel log on this page, I want to have a delete button underneath each of these images. And we extracted this out into a component. So, let's add a slot to that component so I can pass down a delete button. So, let's check out a branch. This is ticket number 43. And then in the code, let's head to that image list component. Now, right below the image here, I want to show a delete button. So, I'm going to add a slot right here. So, we can render out that delete button. And in this case, the individual image itself is not a component. It's the overall element.
So, what I'll do is actually expose the image to the slot. So, on the other side, when the delete button is clicked, we know what image it was clicked for. So, right here, I'm just going to bind that image. Now on the manage images page, we will pass down that slot. So we have our image list and then we want a button inside of that slot. It just says delete. I'll give this a class of button button error. And then if I want to get access to that image that's passed down to the slot. We will then have our template and we can ask for the vlot and then dstructure the image here and then make sure that button is rendered inside. Now when we click this button, let's just log out the image to make sure we're getting that one specific image. So we'll add a click listener and then here we'll call a function called delete image. We will define that image right up here. This gets access to an image which is a select location log image. And then for now we'll just log it out. And we'll be sure to pass that image in. And we do have a variable collision cuz I do have that state variable called image. So let's actually just call this the item. And then we'll
pass that in here so we don't have a name collision. Now let's test it out. So the delete button shows up. That's great. When I click it, if we look in the console, it is logging the reactive value. So, let's actually log to raw. So, we can see the actual thing. So, we'll do that. Now, if I click it, we see this is the image with ID 2. And if I click this one, this is the image with ID 1. So, depending on which button I click, the correct image is being passed back up. Now, let's make this button a little bit smaller. So, let's do a button extra small. So, that's much better. And then, let's also add an icon to it. So, I want a trash can icon.
Let's see what we got. Yeah, we'll use the same one that we used in the other spot in the app. Pass that in. For the size, let's try 18. That looks good. And now when we click this button, we'll show a dialogue so the user can confirm that they want to delete that image. So let's grab our app dialogue. I'm going to copy the instance from this component. Create an instance on the page here. We'll say deleting this image cannot be undone. Do you really want to do this? Yes, delete this image. We'll set up our state variable is open. And then also our confirm delete function.
So here we'll have is open. This will default to false. And then we'll need to keep track of which delete button they pressed. So let's also have the deleting image. This will be of type select location log image or null. Starts off as null. And then when we click that delete button, we'll say this is the image that we're trying to delete. And then we'll set is open to true. Now for on closed, I'll also have a function so we can reset that selected delete image back to null. So let's call this on dialogue close. So when the dialogue closes, we'll set that delete image back to null and we'll set is open to false.
Then for confirm delete, we want to close the dialogue. So I'll set is open to false. And then when we click that delete button, we actually want to open the dialogue. So right here, I will say the deleting image value is the one that we clicked on and is open is now true. So now if I click this button, we get the dialogue. Yes, I want to delete this. We should have seen that specific ID logged out. Yes, I want to delete this. We see that specific ID. So now we can actually make the request to the API. So let's head to our server folder.
Now each image has a specific ID. So I'll create a new folder in the location slug ID folder called image. And then inside of there I'll create an ID with brackets delete.ts. So this will allow us to delete that one image with that ID that belongs to that log that belongs to that location with that slug. So if we take a look at whenever we're creating the image, we're going to do some of the same validation. Essentially, we need to make sure that the location exists and the user owns this specific location.
So, we'll copy that codes. We'll validate that all of that stuff exists. We also want to make sure that this image ID is a number. And I'm realizing we have a conflicting param name. We have ID and then we also have ID here. So, let's be more specific about this. We should call this image ID. So, to validate that image ID, we can use some very similar code like we did earlier where essentially we grab the image ID from the PAM and then make sure that it's a number. And we'll do that before making sure the location exists. So we want to grab the image ID param stored in image ID. Make sure it's a number.
Bring in zod. And here we'll say invalid image ID. So if the image ID is valid, if this location and log exist and the user owns it, now we will delete the image. So we'll say the deleted image will be a call to our queries and we'll say delete location log image. We'll pass in that image ID as a number and we'll pass in the user's ID. Okay, so event.context do user id. So this will make sure that the image that you're deleting we actually own. So let's define this function delete location log image. If we head to our queries, we'll go to the location log image queries.
We'll export this as an async function. This takes in the image ID and the user ID. Both of these are numbers. We'll then grab the deleted image. This will be a call to db delete from the location log image table where the image ID is this and the user ID is that. So let's copy one of our where clauses that's doing something similar. We want like this and clause. We'll import and and equal from drizzle OM. We want to say where the location log image ID is equal to that specific image ID and then where the location log image user ID is equal to that specific user ID. We'll return what was deleted and then return it from the function. So, if this wasn't found, that means that either this image didn't exist or the user doesn't actually own that image. But we'll return it here.
And then over on the other side, have access to it. Let's import this in. And we're getting a syntax error because we need to call this deleted cuz delete is a reserved keyword. So the deleted image is here. And if we did actually delete something, then we also need to remove it from the S3 bucket. After everything, we'll just send back a 204 no content. So we'll say set response status for this event, the 204. And now we'll delete it from S3. So let's create an instance of that S3 client. We have that handydandy function create S3 client.
We'll import that in. And then we'll want to create a delete object command. So if you remember earlier for whenever we were adding the image, we did that get object command. Very similar, but there's one called delete object command. So we have our command. This will be a new delete object command. The bucket name will be env. So we'll import that in S3 bucket. And then we can also specify the key of the item we want to delete. And for that we can just use the deleted thing that we found in the database. So we'll say deleted key. And then finally we'll send the command. So we'll await client.end that specific command. So this will actually delete it from the S3 bucket. Now let's call this endpoint from our front end. So right here is where we want to do the delete.
Let's add a loading variable for whenever we're deleting the image. So we'll say is deleting start off as false. And then let's also have an error message in case anything goes wrong. So we'll call this the delete error. starts off as the empty string. We'll then have a try catch. We'll use dollar sign fetch to make that delete request out to this endpoint here. We'll pass in all the right params. We'll then make this an async function. We'll await this. We'll set is deleting true. Reset the error message if there was one. And then when all of this is done, we'll set is deleting to false. And we'll reset deleting image back to null. Now, if there was an error, we'll show it right next to that image. So we can grab the instance of the error which is E as a fetch error. We'll then say error message dov value is get fetch error message with that specific error. Now let's use all of these variables inside of the UI. So if we are deleting I just want to show a loading spinner on that delete button and we'll also disable the button. So this button should be
disabled if the deleting image is equal to this specific image. So if we're deleting this one and is deleting is true and then same scenario if this is the case we'll show a loading spinner instead. So let's have a div give it a class of loading loading extra small and we'll only display this if we are deleting this image and is deleting is true otherwise we'll show the icon. Now when we're done deleting we should refresh the current location log. So that way the image gets removed because we have the latest value from the database. So here we will just await location store.refresh refresh current location log. And one last thing in the URL here, this doesn't come from the params. You probably caught this, but this is the deleting image value ID. So the specific image that we're deleting.
Now, we can do an early return here if the deleting image doesn't have a value. It should. There's not really a way to get here if it didn't, but we will do that early return. So we can expect that it exists. And then one more thing, we need to make sure that this is sending a delete request. So the method here is delete like so. All right, let's give it a try. So I click delete. Yes, I want to delete and it fails. There is one issue.
So I went ahead and logged out the params that we're getting here. And when we have a dash in the ID, I thought it would camelc case it by default, but it doesn't. So looking at the logs, we actually get image- ID. So when we're getting that router param, we actually need to do image dash ID. So now with that, let's give it a try. We say delete. Yes, I want to delete. And it's gone. And we can delete this one too.
Fantastic. So if we look at our checklist, we have a delete button. We've got our confirm dialogue. We've got that loading spinner. And then we are handling errors. But I'm realizing now we set up this delete error variable. We're not using it. I think setting the delete message is completely fine. So we have that. It's removed from the database. It's removed from the S3 bucket. It removes from the view. The user can see that it got removed. And we have that delete button. So that's it for this one. Now we had one more story on the backlog where we would create an image gallery. I'm actually running out of available time in what I can upload to YouTube for this tutorial. So, I'm leaving that as an exercise for you. I will let you know there is a Nux module called Nux easy lightbox. This gives you this lightbox plugin called View Easy Lightbox that gives you a nice little full screen gallery. That might be one way to do it. You could also implement it yourself with the dialogue, but we're not going to implement it in this video.
That's an exercise for you. All right, let's add this commit, push it, and move on to the last thing, final deployment, and a little bit of cleanup. All right, there's a few last things that I'd like to do before we call this done that I kind of noticed throughout building the app. And the first thing is we need to add attribution to our search form. So we're using that nomenatim API and in their usage policy they mention have attribution. So I think what we'll do is right on the search form here just have a little note that says results provided by nomenatim. So let's check out a branch and then if we head to the place search component right above the search box here we'll add that attribution. So I'll add a div. Let's make the text fairly small. So let's do text access.
final fixes
And then I'll also make it itallic and just say search results provided by no minimum. And then we'll link off to their site. And then let's make sure this link opens in a new tab. So let's set the target to blank. And then we'll add a rail of no opener no follow. And then I want to push this text to the right. So let's make this a flexbox and just do a justify end. And then we'll give this link a class of link. So that way we can click it. It links out. So it looks good. There's no space there. So let's actually just wrap this in a span and then give the flexbox a gap. So it puts a space between the colon. So we'll just give this a gap of one and then remove the period. Yeah, that's what I like to see. So now when people use our app, they know that those results are provided by nomenatum and it links out.
All right. Next up, there is a bug in our date select. I referenced this a couple of times, but if we head to a location log and we go to edit the date, watch what happens. So, let's say I choose the 12th, it actually shows up as the 11th. And this is actually a time zone bug. So, the way that we're formatting the date right now, it's actually using the UTC time. So, if we head to our utils and format date, when we get the full year, month, and day, this is the time according to UTC. And I am in mountain time zone which it differs between 6 and 7 hours from UTC.
So this is the day according to UTC. And if we want to get the day according to the time zone that the date was created in. We'll have to do that inside the date component. Now at this point we probably should have used a date formatting library. It most libraries will take into account the time zone. But a quick fix is if we head to that date form field here. Instead of using the format date function, we can actually just use the ISO date and trim off the remainder. So to see this in action, let's actually create a date.
And there's a few methods. One of them is two ISO string. And you'll notice that this has the first part in the format we expect, but then there's like a time stamp on the end. And what we can do is use this method split on the T and then just grab the date from the beginning. And that will respect the user's time zone. So let's just create a new formatter function we can use internally here just called format date ISO. It'll take in a value which is a number and then we'll return a new date with that value. We'll say two ISO string split it on that capital T and then grab the first part. So this will be sure that that date is in the user's time zone that they selected. So here we'll do format date ISO and that should fix the bug. So now if I select a date that's the date that shows up and also if I enter in a date manually that's the date that shows up. This is the behavior we want. Next up is a minor one but I still want to fix it. So everywhere in our API functions whenever we were returning an error I was using this send error function. This is actually a much older thing. You don't have to do this anymore. We can actually just use create error directly. If you look in the nux
docs you can literally just say throw create error instead of send error. So send error comes from H3 which Nitro is built on top of. So technically it still works but to make sure that we're using the the latest standards according to Nux we should just throw those errors. So basically everywhere in my app where I have send error and I'll make sure that we're only looking at our code, not the the built code. All of these I should actually be just throwing create error. So I'm going to go through and update all of these. Basically instead of this we'll say throw remove that extra parenthesy and the app will behave exactly the same way except we're we're doing things that are much more standard. So I'm going to go through and update all of these. Okay, so I've gone through and updated all of those. I am just going to run really quick a type check and make sure that that didn't introduce any any weird type errors.
shouldn't have, but I'm just going to check to make sure. Yeah, and we're good to go. All right, next up is another issue with our database schema. So, you may have noticed this when you were testing things out, but if we try to delete a location log that has images or a location that has location logs, it will actually error out because of the foreign key reference constraint. So, check this out. If we're on Denver live shows and let's say I just want to delete Denver itself, when I click delete, this actually results in a server error. And that's because the database will not let you delete something if there's a foreign key reference and those things still exist.
So we actually need to update our database schema. So if we head to lib db and then schema for each of these tables where we have a foreign key reference we want to say ondee cascade. So at the top level if we look at our location table if a user ever gets removed from our database we want to delete all of their data. So where I have this user ID foreign key reference, I actually want to say right here onddelete cascade. And what that means is if a user ever gets deleted, all of their locations will be deleted as well. But we need to do this for every table related to the location table as well. So if we take a look at the location log table, we'll of course add it to user ID, but we definitely need it on location ID. So this is what will allow us to delete a location that has multiple location logs. Essentially, if there's a log that's related to some location and we go to delete that location, all of the related locations will be deleted as well. So, we'll add that there. And then, of course, we need it on the images as well. So, here under user ID, we'll add it. And then we'll also add it on the location log ID. So,
if we delete a log, all of its images will get deleted. Now, the one caveat here is the corresponding images that exist inside of S3 aren't going to be automatically deleted. Now, I'm not going to do that in this video, but there are a few different ways you could handle it. First, in any of the delete endpoints. So, if you head to the server, any of these endpoints that delete something should also find all related location logs that have images and then it could fire off the deletes to the S3 bucket to make sure that those get removed. The other thing you could have is a separate task or like a cron job and it could go through and read the data in the bucket and if a particular user has been deleted or a particular log has been deleted go through and delete all of those images as well. Now I might do a one-off video showing how to do that but like I said we're not going to do it in this video. So we have all of these ondee cascades. So let's generate the migration apply it to our local database. Make sure everything works locally and then we'll migrate our database in production as well. So if I do a pnpm drizzle kit generate. So that generated the migration. If we take a
look in the DB migrations folder, there it is. And honestly, this is a little bit messy because the way that this is handled is it actually creates a new table that has that ondelete cascade, inserts all of the existing data from the original table into that table, renames the table, and then deletes the original table. Now, this is fine if we already had users in production and we needed to make this update. This would be totally fine. But like I talked about earlier, we've been in development this whole time, and I like my migrations to have a good starting point. So, what I actually will do is one more time, I know I said we might not do it again, but we're going to do it. I'm actually going to delete the migrations folder, start completely from scratch, and that way I have a fully accounted for base migration. And from here on out, because we are going to production because this this video is getting released, um, if we need to make DB changes, those will happen as migrations. So I'm going to delete the migrations folder. Generate a base migration that takes everything into account. Delete the database in production. Delete my local database.
Start everything from scratch. So let's delete this migrations folder. Generate the base migration which will have everything inside of it. And so now each of these tables has this ondee cascade for any of those foreign key references. Now locally I can heal my database. I need to remove these local DB files. Spin our database back up. Now we have a completely blank database. And now I can do a drizzle kit migrate. And that'll apply those migrations to my local DB.
And if we refresh, everything is gone and I'm not even logged in anymore. So I need to do this same thing on Terso. Essentially I'm just going to delete the existing database, create a new one, generate a key, specify those values in my local.env. So that way I can migrate the production database, update my values inside of Versell, and then we'll have a completely fresh database in production as well. Okay. So I created a new DB, went through Versell, updated all of my settings, migrated the DB by setting those environment variables locally. Now one more thing is we need to create an example file. Now I've been the only developer on this project the whole time, but now other people are going to potentially pull this codebase down and they should have a good starting point for what environment variables to set. So I've gone through and updated everything to remove anything secret, but essentially we want to have this in an example file. So here, let's create aenv.example. Put all of this in here.
And we might add a few notes. We'll say pretty much everything is required except for these. And we'll just say these are only required if running minio locally because it's possible someone pulls the codebase down and then just directly points it at an S3 instance. So they may not need these. But now that I have this, we actually are going to commit this to the repo. And that way whenever someone pulls the codebase down, they'll know these are all the environment variables that they need to set up. Now along with that, let's let them know in the readme that they should set all of that up. So when you pull this down, first we need to create av file. And they can do that by just copying the existing.example file into aenv file.
And then we'll say and update with your values. So all of the environment variables I think are pretty self-explanatory like it's it's in the name. Um, but in the future, maybe we'll update the readme if if people open issues, like they have an issue of creating certain ones. But this should be good enough for our readme. Now, because our app is now running in production, this is the perfect use case for Sentry. So, I could not have made this video without Sentry. And the least you could do is just try it out in your apps in production. So, if you head over to Sentry.io, you can learn all about it. Essentially, if anything goes wrong in production that you didn't account for, like some error that wasn't caught or something's going wrong, that will be reported back to the Sentry dashboard and you'll get a nice summary of what went wrong so you can fix it. If you head to century.io/sintax, you can actually get too much for free if you use code tasty treat. I highly recommend it. Just sign up and we're now going to add this integration to our app. So, I'll show you how to do that. So, first up, I actually need a project inside of my Sentry dashboard. So you can see here
nuxt sentry setup
they have all of the things that you can choose from. We of course are going to choose next. You can choose your notification settings. I'll give it a name and we'll create the project. They give me the exact command that I can run. So I'll throw this in here. That launches the browser and connects the project locally. There is a temporary fix that needs to be applied. So we can say yes to this. And then we choose our deployment platform. So of course we deploy to versel. I'll choose that. And then we can enable tracing. So this will track things like performance of database queries and other stuff like that. So I'm going to leave that enabled. And we also have session replay. So if something ever goes wrong, some sort of error, we can actually see exactly what the user was doing when that error happened. So this is super useful. And we will create this example page so we can make sure that the error reporting is hooked up once we have it deployed. Now this created several files and we do have our llinter set up. So I'm going to go ahead and run a lint fix just to make sure that everything adheres to our preferred code style. And there's a couple of issues. So if we head to pages sentry example page, this wants the root to have a single element which we can do. So I'll just wrap it in
a div like so. And then we have an error variable that is not used. So we'll just remove that there. That should be good. Awesome. So no lint issues. If we take a look at the git log, we can see everything that changed. Mainly we have our nux config. So this added the centry nux module and then added our initial config. So if you need to modify anything, that will be in here. Then we have our client configuration. And so Sentry runs both on the client and on the server. So anything happening either on the client or the server, we can see the full span of where things started when an error happened. So we can do a full trace from front end to backend.
You can see all of our default settings in here. And then also our server config as well. For both of these, we have our DSN set here. And then we have that example page which basically fires off an error to the Sentry dashboard. And then an example API endpoint. Now, I don't want to commit my DSN and my org setting in project name to this repo because you're probably going to pull it down and then you would be reporting issues to my Sentry dashboard. So, I'm going to set up some environment variables. Now, I don't want these environment variables to be required because you might be pulling this code down and maybe you don't want to report errors to Sentry. So, I'm not adding them to my type safe env. I'm just adding them locally and also putting them in my example env. because they're not in my type safe envir convention. So I'm saying import meta.env and then grabbing those two values. VIT will make those available during the build process. And then in our client config, we're pulling from import meta envydn. It's important that this starts with vit so that way it's available inside of client side code. And then we
do the same thing in this server config. So here are all the issues that have happened. We can see the most recent one. And if we head into there, we can actually see the error that occurred, see what code was running on the front end and on the back end. Sentry also has session replay. So we can click play here and we can see exactly what the user was doing when that error happened and everything is anonymized. In this case, I literally clicked the button.
That's what fires off the air. But Sentry is fantastic, especially because this app is going to be available to the public once this video goes live. And so people are probably going to be messing around with it and I'll be able to see all of the issues that pop up here in the Sentry dashboard. So Centry is great. You definitely should use it if you're running apps in production. Okay, so we've fixed all of these. Let me add everything, commit it, push it, and we'll do one final test in production to make sure everything's working, and we'll call it done. So, that final fix was deployed. If you take a look at issues and you use the project board creator at the beginning of this video, all of these epics are now complete except for image management. So, essentially, all of the sub stories we worked on, those are finished. And you can actually see the the subtasks marked off here except for the image management one. So we are going to mark these as completed. Awesome. Now all there is to do is give it a try. So if we head to our app running in production, we'll try signing in. We're in. And now we can start creating. So first of all, let's let's check that delete of a cascade. So
final deployment
let's go ahead and just put Denver on the map. Add some nested info. So we've got Denver. And then in Denver, let me just add Kasab Bonita. So yeah, set it there. Give it a name. Add it. And now under Kaza Bonita, let's add an image like that one. It's uploading. It uploaded. Sweet. Uh, and now here's the thing to try. If we go back and try deleting Denver, this should do a delete cascade. So, it deletes Denver. It deletes Casa Bonita. That image is still hanging around. Like I said, we need to add some kind of job that deletes images that are no longer in use. But, we have a working app. Fantastic. Thank you so much for watching to the end of this very long video. Hopefully there were some good little nuggets of information throughout. If you enjoyed this video, the best thing you could do for me is to share it. Share it with someone who's trying to learn Nux. Share it with someone who's trying to learn Vue or about full stack development. That would mean the world to me. If you have any questions, of course, leave them down in the comments. If you have any heavier
thanks!
code questions that won't exactly work as a YouTube comment, join the Syntax Discord. So, I'm going to be creating a channel in there specifically for the Nux Travel Log. And if you're going through this tutorial and you hit some snags, throw a question in the Discord and I or someone in the community will try to get back to you. So again, thank you so much for watching this. I hope you've had a ton of fun building with Next. I hope you're going to keep building with Next and I will see you in the next one.
Quote it with credit and a link. Quoting Syntax