Unlocking Powerful State Management in Nuxt 3 with Pinia

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
welcome back guys uh today I want to explore one of the modules provided by the community and that module is the Pina module so I'm going to show you how you can actually incorporate the pinion module into your nox application um let me just go through documentation this will take you to the pineal website and if you click on the get started button and then go down to the server side rendering SSR section you see a nox.js section cool so um what will be what I'll be showing you today is um just a simple website if you want to call it that where I Implement authentication so if I'm logged out I cannot go to the profile page you can see where it redirects me instantly to this um home page or sign-in page and if I click on sign in them redirected to the profile page and if I try to go back to the sign in page it redirects me into the profile page because I've already signed in cool so you know without further Ado let's just jump into the code all right so we have vs code open and I'm just gonna go ahead and create a new nox application so we type in npx noxi inips and in the name of the follow but I already have the folder open that I want to create my project in so I'm just going to use a full stop press enter and this creates the nox application these are all the files that you get with a new nox application with this um in it command so we want to go ahead and install the dependencies you can use npm but I'm going to use yarn I switch from npm to yarn because I think it's better cool so if you are if your npm user then go ahead and use npm I'm a yarn user so I'm going to use yarn all right so all it dependence is installed let's go ahead and clear the terminal and next we want to go to the pineal website and we're going to go to let's see where is it here so from the Knox website um you know if you go to knox.com click on modules modules I already know that then we have the pinion module it's one of the top modules so um if you go to the documentation like I said click on get started go into this section the server side rendering section click on Nooks then it will show you or you can actually add Nooks to your or add pineal sorry to your Knox application so what we're going to do is we're gonna copy the yarn command right um if you're an npm user you can copy this one let's go back to uh or code base and we're going to paste that in we're going to add that there once it's added then we'll just go back to opinion website or documentation and like it says here you're using npm you might encounter an ER solve our e resolve unable to resolve dependency tree error in that case add the following to your package.json file so if you're using npm on you run up into this e-resolve error just add this to your package.json file cool so once it's installed we can go ahead and add the pinionox module to our modules array so let me just go ahead and do that so right now we can just open this file and then we want to paste it's right here and I realized that my Nooks R extension is not on the left so I'm gonna reload the window I should come up there it is nice knock star Etc you should use this extension if you are a Nooks 3 developer all right cool so we have the module added um just for basic styling I'm going to add the Tailwind CSS module but I'm not going to add it manually I'm going to use the knock star extension so I'm going to open my command palette type in frame and you can see the option to configure CSS framework I'm going to use Tailwind I'm gonna check all of these boxes to install the module create the config file and create this CSS file so I'm going to click ok and it will do its thing so it's going to add the module install the different dependencies create the files and then it will actually open the config file for the for Tilly so here it is detailed in config file now to my configuration I'm just gonna um extend the content container configuration so I'm going to make it Center and I'm going to increase the padding so for this pattern I'm going to say the default should be one REM I'm just gonna allow GitHub copara to determine different sizes that I use cool click on Save and that's it for Tailwind well almost it um I realized that the module doesn't actually add the semicolons to the end of these things so I'm going to add them here click on Save and now that's it for the children CSS module next up we want to configure the app.view file uh this will give us the Knox welcome component so if I should run this up no so it's a yarn there right so the app is running if I should open localhost 3000 in my browser see where the application is starting up and it gives me the welcome page from or the welcome component from Nooks that's shipped with the in its um command by default but we don't want to use this we want to use our own page right so we're going to go back to our application let's stop the server I'm going to say that we want to use Linux layout and this limit is coming from a knock star extension another reason to get it and the notes page and of course you want to add your loading indicator so that your user knows when you are making a request to transition to another page or something like that so we're going to save this and then we're going to come here right click and we're going to select create Knox project directories now the directories that we want we want the Pages directory logins directory you want the middleware you want the stores because we're going to use Pina and see if we want anything else I don't think we need anything else so we can go ahead and create these and you can see it just added the different folders so the middleware folder Pages Fuller and you created an index of view page on the plugins folder and the stores folder with nothing in it cool so first thing that we want to do is actually create or store but before creating the store let's do some configuration with pinia right so it goes to our Nooks config and we're going to say hey Kenya right I need you to do this I need to also import the Define store function that comes with PDF so we're going to put that here and we can see in the documentation where it tells us to do this let me just close this one so if we want to Auto Import stuff we can just use this and if we want to rename the import then we can use this syntax cool so I'm going over to our code and we want to Auto Import Define store compose your function that comes from India also we want to turn nox that it should import everything from this stores folder so if you want to add Auto Import to your project for folders that aren't supported by Nooks from the get-go then you can add the folders to the deers array we're gonna say that we want stores to be one such follow that everything from root files are Auto imported we have nothing in it no but we'll add or store to it shortly so um everything that's Within These stores follow will be Auto imported cool so we save that and that's it for our Linux config no to or stores right so for stores we're gonna say right click on the stores follow and click create a new store and the noxar extension actually allows us to um enter the name of the store I'm going to say that the name is USO you will create a user.ts file and it will scaffold this store for us now Pina actually allows us to Define our stores in two ways we can come to the documentation and click on the Define store link and we'll see where we have an options store option stores and the setup stores uh options uh not my favorite I go with the setup store but you can definitely use um this way of defining a store or this way um the setup allows you to use like ref and you know the new three syntax but the option store um allow you to do like a state get us action similar to ux if you're familiar with ux well like I said I'm going to focus on using the setup stores in this little walk through so we jump back to vs code and we're gonna remove all of this right because this is the options way of doing it where we have the ID the state actions get us and all that stuff by type getters you can see where I'm getting the auto complete another so let me just go ahead and remove this and I'm going to export a consent last name user use user store and it's going to be equal to Define store so Define store is a function that accepts as the first argument the name of the store so I'm going to say this is called use all right and the second parameter is a function with everything that you want to return from the store cool so what am I going to have in the user store so the user store is going to have a user obviously so I'm going to say ref and that can be node right so we're gonna have a user and we're going to also have a token cool no for our token is going to be um use in conjunction with the use cookie composable that comes from Knox and we're gonna call this one um so the first argument to the use cookie composable is the name of the code so we're going to say uh my cookie of course you want to make this more secure it should make more sense than my coffee uh let's see the second argument is actually an object with the list of options that you want to use with this screen now for this tutorial we're only going to use the max Edge and the max age option is the time that it will take for the cookie to expire in seconds so I'm gonna say here that it should expire within an hour so one hour in seconds is 60 times 60. next we actually want a function to set our user and set token so this is going to be here concept token and we're going to accept data this can be null or undefined or a string and what it's going to do is going to say token dot value is equal to data and we're going to do the same for user where we're going to say the user can be any for no and the function is going to set the user value to whatever data is passed in cool no within this use user store Pina store you want to add a function that will actually sign the user in so we're going to create a sign-in function and this sign-in function is going to take the login information which for now we're going to say this is any and then we're going to create a try catch block right so if the request assigned the user in fields what we want to do is we want to set the token to null so we're just going to call this a token function and pass nothing if you pass nothing then the parameter will be undefined and the value for the token will also be undefined full next we want to say set user and we want to pass nothing to this so that we will set the user as undefined and lastly we want to log the error out so we're just going to log the arrow right there now within the tripart of the function we want to send the request to some API or the sort so this would actually be a request to whatever API is authenticating your user in this walkthrough I'm going to use a dummy rest API and if we go to dummy json.com we'll actually find some endpoints that we can actually hit the one that I'm looking at for logging in is actually this um login and get token endpoint that they provide shuttle to this author whatever the author for this is so you can see here we're saying to send our post request to this endpoint so I'm just going to copy that and we're going to jump back to vs code and add this here so we're going to say cons res is going to equal to a weight and we're going to use a fetch composable provided by nox and then we're going to say the type that's returned by this fetch request is any for now and then we are going to say we want a fetch request to be sent to this endpoint one that we just copied and then we're going to pass options to refresh request now the method as stated on the website it's a post request so we're going to copy this as well go back to the code and paste that in the method should be paused and then the data has been sent is going to come from wherever this function is being called from so we're going to say the body is going to be data save that no this endpoint will actually return to us it is output so if you click on show output right here you can see where we actually get a token back from this um endpoint no I want to actually create a type for um this response so what I'm going to do is I'm going to copy this object I'm going to go to up that quick type.io I'm going to paste it in and I'm going to call this user and you can see where it created the type for us automatically now I have this interface only thing checked right here if I uncheck I mean check if I uncheck it then you can see all of the different functions and stuff that the of that quick type IO will return to us but if I only want to type then I can go ahead and check the interfaces only option change this to typescript of course and then I can just either copy it like this or I can click on copy fold doesn't matter so then we go back to our Nooks application and I'm going to create a types file so I'm going to right click create a new file call it types.ts and I'm going to paste that in here 4 whether you want to use an interface or a type doesn't matter um it's going to do the same thing so I'm going to copy this user type from this types file then I'm going to go here I'm going to say the response type should be of type user right then I'm going to import it so if we save that and hover over this response then we can see that it's of type sir cool now once we get this response then we're going to set the token to the Token that's passed back from this user type so we're going to say res and we want the token property we're going to pass that string into the set token function and it's going to create this token and store it in a Coffee Card so no we also want after getting the token we want to get the user details right so what we're going to do is we're going to create a separate function and we're going to call this fetch customer and this is going to be an asynchronous function and what we're going to say is if token the value well not not so if token of value then we want to execute this function cool so we're going to wrap it in a try catch block no in the cat section or the catch block if there's an error of course we want to set the user to undefine and we're going to log whatever that error is so let's save that but if we have no problems this is what we actually want to do so we're going to say cons response is equal to awaits and we're going to use the fetch composer plugin and we are going to call this endpoint from or dummy API so come down here we have a user section and we can get a single user all right so we're gonna actually send a request to this endpoint so let's copy that and jump back to vs code and paste that in here and this is a get request so we don't need to pass any options but if we get a response we want to actually set the user with whatever is returned from this endpoint and to have an idea of what's returned if we click on show output on the website you can see that we get this big object of course we're not going to manually create a type for this object so we're gonna come up here copy the output go back over here and paste it in and we're going to call this customer right and of course we have all the interfaces so we're going to copy them we're going to go back to vs code and in our types file we're just going to paste them right in hit save and of course we want to copy the customer interface we're going to go back to the user store and we're going to say that the response from this endpoint should be of type customer of course we have to import this from our types so up here we import it and hit save and that should be it for or fetch customer function within our user store now back to the sign-in function right so after you sign in and you store the token in the cookie we want to await the fetch customer function so once the user signs in uh we'll set the token and then get the customer information from this function cool so this function is what we'll actually use to send a request to the API to get by the details on this login person once the token is defined because nothing will happen in this function if this token is undefined or falsy right so once this is defined then we'll send the request and set the user cool of course we need a function to log out so we're going to say cons logo this is going to be a function and all it's just going to do is set the token and the user values to undefined cool like I said uh the start of creating this um store we can't use any of these unless we actually return them so at the end of the file we're going to say hey I want to return from this opinion store so two again logout function I want the sign in function the fetch customer function and if you want you can actually export the set user and set token functions so I'm going to hit save and that should be it for or store cool no in order to get the user whenever we refresh the page we're going to create a plugin right so we're gonna come here and let's see let's close these files and in an empty space I'm going to right click I'm going to create another folder well I don't have to I already have the plugins folder here so I can right click on plugins and create a new plugin and the name of this plugin is going to be off just like that we have the auth plugin cool so what are we going to do in this plugin in this plugin we are going to first make it asynchronous right and then we're going to bring in our store that we created here no we should have Auto Import um functionality so we could say user store is equal to and let me just look up the name of this store use user store of course well we have this little Reds quickly and the reason why we have that is because we need to run the post install come on again from Nooks to generator types so I'm going to go here in the knock star extension click on the plus post install action and once the types are generated I can go ahead and hover over this and you can see we're actually getting the up Auto Import functionality from Knox with this pina store right so what do I want to do in this plugin so in this plugin I'm going to say if the user is not defined right then we want to actually call the fetch customer function from this pinia store so if this person is undefined then we're going to call it fetch customer function and the fetch customer function like I said earlier if the token is defined and not falsy then it's going to reach out to the API get the details for the logged in person and then set the user cool so let me save that and that's it for this uh plugin so next we want to work on our pages right so the index page is going to be a simple page um let's just add a little bit of styling I'm gonna say this should be a container I want it to be here Flex continue item should be centered Justified centered right and inside of this I actually want to add just all the text that says welcome and below that something to say hey to the user sign in to your profile and then I want a bun and this button should have the text sign in all right so let me add some classes to this I'm going to add some pattern left and right button top on bottom add some roundness to it I'm gonna make the background Emerald 500 text gonna be white it's gonna be inline Flex item Center justify Center let's save that and then in the script setup part of our um single file component we're going to import or Pina store no the opinion documentation actually tells you that you should not destructure the store when you're importing it right so don't do don't do this don't do this type of thing so if you want something from the store don't don't do it like this it's better if you actually do it like this and then you call the different properties or functions that you want of of this object cool so we want a sign in function so let's say cons sign in this is going to be an asynchronous function and inside of this function we're going to call the sign in function from our auth store so it should be await or store Dot sign in right now the sign-in data according to the Domi API website should be this of course in a real application you'd actually create input fields to get this information from the user but as I'm just demonstrating how pinia Works in Knox um I won't actually go through getting the username and password from the use of here some input field so we'll just copy this thing and we go back to the code and we paste it in right there no if you want the help of typescript for these two um or this parameter that should be sent to the sign-in function you can actually just go in our types file export an interface called plugin and it's just going to be username and password and of course we can come into our store and say that information that's sent to the sign-in function should be of type login and of course we want to press Ctrl full stop and import it from the types file so hit save and then this will be typed properly so your user doesn't just enter anything that they want to enter now after sending this request to the endpoint or calling the sign-in function we are going to navigate to a new page right so you want to say await navigate to and we're going to call this page profile and we can pass an option to the navigate to composable and we're going to say replace should be true because we want to replace this route cool so we're going to create the second profile page right I'm going to right click on pages create view page I'm going to say profile and this profile page is going to be similar to the one to the index page here let me just quickly add the Styles I want it to be a container ui5 um I'm not going to make the flex container I'm just gonna say minimum height should be screened and then inside of that you're gonna have ch1 access profile and uh probably just uh a lot of open just say sign oh and I'm gonna copy the styles from this button over here paste it over here so they look the same oh we made this red yeah all right so on the index page we are not currently doing anything with the sign-in function so let's add the quick event to the bottom and call the sign in so if I should run this and go back to our website we can see where we have welcome sign into your profile and let me just open the network tab to see if anything will go wrong if I click on sign in you can see where I got logged in on in the network tab we actually have the request being sent to the endpoint here and it's returning this object and then after logging in I sent a request to the user's endpoint and the response is this big objects now if I should come to profile in our code let's say I just want to dump the user on this page I can actually come here and say cons to store equal to use user store and then I could say something like free user store.uso and dump that dope right there let me see if that will actually persist and there it is so this is the user from the PDS store um pinia also has its own extension but it's not here right now I would have to reload page but if I reload the page you can see where the plugin is actually recreating or user all right so the plugin that we created earlier called auth um once I reload the page the user becomes undefined and if the user is undefined then it sends the request to or it cause the fetch customer function now the fetch customer function we'll check if we have a token and the token is this mic token and once this is defined then our request will be sent to the get a single user endpoint and then the user will be populated again no if we want to actually protect this profile page so that uh if you're not logged in then you can't just come to the page so if I delete the cookies here right and I go to the profile page you can see where I'm being logged in even though I cleared um the cookie here so if I click on this you can see that I'm still on the profile page which is not what we want cool if we don't have the cookie in place then the user shouldn't be able to access this page so how do we fix that well we fixed it with middlewares so in vs code we're going to create two middlewares the first one being already authenticated now if you're already authenticated then you should be pushed to the profile page right so let me go ahead and create this already off middleware so you can see here we're right clicking on the middleware folder we'll ask you for the middleware name and then the knock star extension will create a file for you and add the actual Define Nooks route middleware function to it so we're going to make this asynchronous and the reason why we're going to make this asynchronous is because we're going to call the away the navigate to composable if the user is actually logged in already so how do we check if the user is logged in already we're going to call the user store right I'm going to say use use a store then we're going to say if the user store.user is defined so if it's truthy that's what is double bond means value is true or true according to JavaScript then we're going to return a weight navigate to the profile page so all this middleware is going to do is check if we have a user defined in the user store and if we do I'm gonna say hey this middleware is registered on this page but it's saying that if you're logged in you shouldn't be on this page so we're gonna add this middleware to our index page so if the user is logged in we don't want them to click on the sign in button again we just want to take them straight to the profile page so we have to actually restart our server for the middleware to be root um registered so we're gonna just restart the server quickly and then inside of this script setup section we're going to say Define page meta cool that is composable will actually allow us to register a middleware and we have two ways of registering middlewares you can just use a string if we're going to use a single middleware or we can pass in an array of middlewares cool so let's save that and if we go back to our website page reloaded if we click on sign in we're taken to the profile page but if we try to go back to that sign-in page you can see where it just redirects us to the profile page and that's because of that middleware so once the user is defined we can't go back to that page so let me just delete this reload this page and if I go back to the signing page then I'm able to do so cool and that's because no we don't actually have a user in our opinion store you can see it's undefined here the token is undefined as well cool so now how do we protect the profile page well it's pretty similar to what we did to protect the sign in page so if we go back to the code we can right click on middleware create a new middleware we're going to call this one off so that will create a file we're going to make this a synchronous and then we're going to say we want the user store so let's let's copy over this user store paste it in and here we're gonna say if we don't have a user so if not use a solar user then we want to tell the person that hey shouldn't be on this page um go back to the signing page we're going to say return await navigate to or sign in page in our case the signing page is actually the home page index page right here so let's save that and in order to use this middleware um we're going to go to the profile page and let me just restart the server quickly what so on our profile page you want to say hey call the Define page meta composable and we want to register a middleware the middleware want to register here is auth so if you try to come to this pH then it will actually run the auth middleware and if you're not logged in or the user is undefined then we'll redirect you to the sign in page cool so let's jump back to the browser and see that in action so if I enter into the URL profile you can see where it just redirects me back to the signing page I'm not allowed to see that page unless the user is defined cool now if I click on sign in you can see where on this side user got defined token got defined in the Pina store user store and I'm actually seeing the user over here no when I click on the sign up button I want to actually log user out until then but to the sign in page so let's jump back to vs code and get that going close all of these files and I want to open profile so when I click this sign open it should actually call a signal or logout function and keep the user box to the sign in page so I'm going to say cons sign out this is going to be a function dot calls user.logo cool no this level function as We Know it will just reset the token and the user but in addition to that we actually want to push the user to the sign-in page and the best way to do that is actually to use use row term composable and we're going to call the go function here and pass in a zero now what this will do is basically just reload the page and in reloading the page we will actually trigger this middleware again and because this middleware will check if the user is defined um and if it's not defined it will actually kick you back to the signing page you will be redirected to the sign in page so just to go over the floor again this button once we click on it it's gonna call sign oh right and the side note is going to say okay call the logout function on the user store and the user server logout function will set the user and the token to undefine and then once that's done we're going to reload the page upon reloading the page we're going to recall this middleware it's off middleware and this art middleware is going to say all right let's check if the user is defined what the user is not defined anymore because it is not a function so it's going to say oh the user is not defined you need to go back to this page cool so let's see that in action so go back to our page and let's refresh again and if we click on sign out you can see here where we're redirected to the signing page and if you look at opinion store the user is undefined the token is undefined and if you try to go back that doesn't work and if we try to go to profile that doesn't work so this is how you can actually Implement your own authentication cool so we're going to hit sign in user signed in which I have to go to the sign in page again you get redirected to our profile and if we click sign out then we actually made the user the token undefined and then where we take into the sign in page so that's the uh pineal module for Knox in a nutshell um of course there's a lot more to learn on the documentation so if you want to dig in and learn about the different caveats and you know what to look out for definitely check out the documentation for pineal um you can use it just like it's telling you in the documentation here in Knox they just have this nox module created to make your life easier while using the the package so that's it for today hope you guys learned something from this video until next time peace
Info
Channel: Behon Baker
Views: 11,880
Rating: undefined out of 5
Keywords: nuxt 3, pinia, state management
Id: owPPfzX1IMc
Channel Id: undefined
Length: 46min 58sec (2818 seconds)
Published: Tue Aug 15 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.