Server Actions in Next.js 14+ | Access Database without Api Routes

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
thank you hi guys welcome to this video in this video I'm going to talk about very important topic in next year 13 which is server actions and server action actually gives us flexibility to write less code on JavaScript and call the apis or access to the database through the server components right and this line is very important that we can Define server actions inside the server components and or called from the client component so in this video I will be covering both of these scenarios and obviously I'll be showing you some easy examples and my own examples to elaborate server actions and it's different scenarios so this is the small app that I've been using in my last couple of videos as well where I showed you how to fetch the data from mongodb create Mongoose schemas create route handlers and call the API to get this data from this database right and I also showed you how we can add other light and dark theming inside it so in this video I will be creating a form above this post section for the title and the description and I'll be creating a button if I click on that button then I'll pass the data of the form to the to the database to save that and I'll be doing it without creating an API and without writing any client-side code right so let's go to our project and just to give you an idea about the product structure so this is the post route and you can see that slash post route and if I click on the post this data is coming from the mongodb database and I'm calling this local API which I've already created and I showed you in my last video and this is the route API slash posts and it is connecting to the mongodb database it's using the Mongoose uh model and calling the find function to get the data and it is returning this data to the client right but this page is is a server our component so we have been learning that when we need to create a form and add a click event then it is it has to be a client-side component like we need to use some use effect hooks or use State hooks to maintain the data of each of the input elements in the form right but this is not the case in server components or if we are using the server actions in the server component so let me show you that how we can create forms on the server side so I'll be creating a new form and I'll be coming inside this container and I'll be creating a new form so first of all if I go to the next dot config.js make sure you have added this experimental and then server actions equals to true if you have not already added then server actions is you cannot use it in your project right so now in this page dot jsx file I'm going to create a new form so form and I'm going to give it a class name and the class name I can give it styles form right and for now let's keep it like this and inside the form I can create two input tags and one button so I'm not explaining you how to write HTML or the CSS so I'll be just being copying few HTML directly over here right and this is the div and div contains a first input which with the label and this is the class I have applied and this is the HTML for title which is uh this title right and second one is for description and the third third one is the button and I've given the type submit to it right and uh I'm going to save it and if I see it's CSS file I've already added some CSS to it like the dot form and Dot input container dot label and if I go to my UI you can see that the form is visible this is the title and this is the description this is the button okay so rather than actually adding the on change events to it and manage the states and add the use effect to handle the to address the change effects I'm going to create a new function with this within this component this function has to be an async function okay and this function we can call it add post action we need to create action for implementing the server action and the first line if we need to create an action directly inside a server component then we need to add this use server inside it inside this function first okay once we'll use it we can fetch that data this variable is going to contain the data of the all the input elements inside it uh this import and this is the text area okay and the name properties are required you need to give the attributes name equals to and we'll be using these values to actually fetch the data of it so I'm going to write const post title equals to data dot get and this is going to be the title and it's always a good practice to convert it into a spring okay and then I'm going to write for the post description and this is going to be data.get to Strings and it is helping me writing code it is suggesting me what do I need to write and the plugin I'm using is actually tab 9 AI assistant you can use this plugin in vs code and it will help you in suggesting some code blocks usually it doesn't give you like this is the code it is suggesting uh it might be right but I don't want to write it I want to store this data in my database but first of all let's verify what's contained inside it so I'm going to save this file and go to my browser and see if it is printed so this is the title this is the description and click add post and it is not printed so the reason is that we are not using this function anywhere in our form so what we need to do is in order to integrate server action we need to add a server action property and then we need to add post action in over here but remember that you need to add type submit over here and the action and these two things will all are only required to actually manage the data of this whole form so if I save this file let's go and now I'm going to add the description add post and here you can see that it has printed the title and description which I added in this form so this is awesome we are getting the data in our action okay and we have actually used form in our server component index.js13 so now I'm going to uh create uh I'm going to call the DB so I'm going to write connect so this has to be from the DB file so you can see that it has actually imported the connect function from the DB file if I quickly show you the DB file so you don't get confused so you can see that I'm just connecting with the mongodb URL and I've stored this URL in my EnV file right that's it and now after connecting I need to pass this data to the database so it actually can save the data in the database okay so the next line I'll be writing is I'll be first creating a new instance of the post model which I've already created if I quickly show you this is the schema using Mongoose which I created okay and inside it I'm going to pass the title and it's actually helping me out writing this so the title equals to post title and then the description okay and then I'm going to save it right and I'm going to just save this file let's go refresh and I'm going to add the new title new description so let's save I've added a post and it is not actually showing this new data so if I refresh the page you can see that now it is visible so why do I need to refresh it this is where the concept comes in revalidation so in order to revalidate the data so we will be revalidate path and it is going to be imported from next slash cache and then I can write simply slash inside it okay so now let's save this file let's go and let's refresh the page and now next title next description foreign the file if it's visible yes it is visible now we don't need to refresh the page so in the server actions you will have to manage that but this slash is going to revalidate all the data that exists on this page so you might be having the other API calls or other uh features or components being loaded on this page so it's not a good practice since this form is only related to get the data for this and not other components so in order to only validate this particular API this is where I'm fetching the data of all the posts using the local API which I created and the next property that I can add to it is the tags and in the tags I can write posts and rather than adding slash I can write posts to it now it will only validate the data for this posts route okay uh that's it and again if I explain you what I have done uh is that we have this route.ts file where I created this get requests and for the post I have not actually created any route Handler or rest API that is responsible for getting the data from the client or from and processing the data calling some apis or directly saving it inside the mongodb database instead I'm not even using any client-side code in this file it is not coming from the client side I am processing this form directly from the server side because it's the server component as I have not written use client at the top of it okay and then I am processing the data on the server side I am just saving the data in the mongodb from the server side so it's always a good practice to add some kind of validations inside it so in order to add the validation I can add the not post title or the post title so I can add the description and it is already suggesting me what do I need to write so uh this is uh if the title or post is empty I'm just returning it from here and it will not be saved in the database although I've already written the required property in the database schema but still on the front and side it's it's good to have that and then since we are using the async await to add a validation we need to add the try catch blocks so the try catch Vlogs I don't know what it's suggesting I don't need this I just need to add it inside here and then in the catch block it will show me some error and then it will show me this log okay so that's it for the server side component and this is where we are creating some actions right so now we are done with the first point this is the point that actions can be defined inside the server components and this is we have already validated but in order to test that the same action can be called from the client component so first we need to create a client component and then we need to call this action the server action that we have created okay so uh before going further just to give you an idea that we can have more than one actions in a component in a server component this is one if you have a 10 or 20 API calls needs to be made on the page and most of them needs to be called from the server side you can have as much actions server actions created directly in this component and you can utilize that just by adding the action equals to add post action okay so now let's move towards creating this action in a separate file so first of all I am going to create a new folder inside my source folder or like outside the source folder as well we can do it so it's better to add it in the source folder and inside it it's what happens I'm going to create actions and inside it I'm going to add a new file and I'm going to name it post action dot Js okay and inside it I will just be copying the same function which I created here and just cut it from here paste it and what we need to do here is to only move this outside this function okay now there are few things that I need to bring inside it like the connect post and the revalidate okay so actually if we just start writing the connect we can get the TB we can remove it now and then we need to add this post so post which is from the model this has been imported and then we have this revalidate revalidate from the next cache okay and I can remove this right and the next thing is that in order to use this function action function outside this file we need to export it obviously so I will be just writing export before the async keyword so now if I come here and uh rather than actually writing anything over here I just need to import that action because I've already used this action over here so in order to import that I will just be removing it from here because these are not required so I will just be adding so let's rewrite it so I it is it right said automatically yeah it is automatically imported and let's save it now still we are using it from the server side and this post action is also on the server side since we are using use server and this is again the server component but we have separated out the actions uh inside it so now let's go ahead and see if it still works or not so let's refresh and we have this data let me verify on the mongodb if it is actually Reef inserting the data inside it or not so it's loading the data and uh yes over data is being added over mongodb so over functionality is working fine so sap separate title separate description okay and add a post and let's come down and it has been added it has been automatically revalidated so over separate file of action is working as is before right this is awesome and now let's go ahead and use this action from a client component so I will be creating a new button below this add post button and I'll be just passing some constant data to the database and I'll be using this action in order to save the data actually right so and then uh let me create a new folder so so I'm going to create a new folder and I'm going to name it add post so let's create a new file so I'm going to name it add post from client Dot jsx and we can have its some CSS file as well so add post module.css and we can update it CSS like this or just be adding some button inside it so I'll just be closing that opening up the uh add post client module and inside date let me first create this and it has been added let me update the name of it with the capital letter and inside it first I'll be creating a button so this button is going to be off type so I'm I won't be giving any type to it so let's give it a class name so Styles dot button all right and for now I'm not going to add any click event to it since it is a client component so we need to add a use client at the top right and since it is a client component again if we create any input element input attribute or create a form inside it will have to import use statehooks or use effect hook as well it up to you how you manage that add on changes events on those uh input elements then we'll be gathering the data Maybe from event.target dot value uh something like that so you can do it you I am assuming that you already know that how to build up a form pass the data to a function and add a submit event for all the form on the client side but uh just to save your time if you can do that you you need to do but I'll just be constructing a constant data assuming that that data is coming from a form which is created on this client-side component okay so first of all uh I will be creating a new data so let's say const form data equals to and this is going to be the title equals to uh client title and then the description this is going to be the client description okay this is the data I've constructed and now in order to use that action I need to import that action so I'm going to uh first let's import the Styles which I've already used so styles from add post module and then I'm going to import that add post action and this has been imported now in order to use that action from it from this button let me add a button uh Glide side button okay and then I'm going to add an on click on click works on the client side as you already know and then I'm going to add an arrow function and then I can add add post action then I can pass the form data to it which I have created above okay so let's save this file and I can add this component in my page or anywhere else so let's try to add this below this button so I'm going to add it add post from client and we automatically imported in this file you can see over here right so let's save it and it should be visible over here yes it's visible and I don't need to fill any data over here because this is the server side form I need to create a client-side form which I have not created I'm assuming you you will be creating yourself since um I have I have I'll be passing some constant data that I've just created as I've shown you so this is where I have constructed this data so let's see if it works fine or not so I'll be clicking client side button there's an error uh what's the error inside it data.get is not a function uh so actually this data dot get function comes from the form data class so we need to convert it into the form data so in order to convert the form data let me show you the form data is from the form data and then the form data dot append title title and the form data is the content content if you said this has to be the description so the client Title One client type client description one okay now you have to create this form data uh once you pass the data from the client components um and then reconstruct the data using this format so I have saved this file and this data client title one client description one needs to be added in our database so let's refresh the page just in case and click on the client side button and go down and this has been added this is awesome and if we go to our mongodb let's go ahead Let me refresh this and this data has to be added in this file okay so let's hear awesome this has been added so guys we are using client uh site component in order to access the server actions to update the data in the database and we don't have to create any route Handler just like the get request we could uh we we if we want we can remove the get request as well we can get the data from the server directly okay and one last thing in this video I just want to show you is some kind of Animation like uh how we are going to handle the process between uh calling this action This Server action and before that that I saved in the database there is some few seconds uh depends upon the server speed so I'll be importing something called a use transition okay so let's add a use transition Hook from the react and I will be adding it like a state so inside date I can have first let me add it use transition and then I'm going to add is pending and then I can write the start transition so is pending is able is Will can give us any Boolean value whether there is a process between uh calling this action and the data is completely processed or not and the start action needs to be added over here so I can write start action with arrow function this and then again like this and then I need to add another parentheses make sure you give it a proper parenthesis and in order to use the is pending I have added the start transition and let's add something like here so I'm going to add uh is pending and I can add a spinner but uh I don't want to do that so posting will be shown when is pending is true so currently style dot spinner is not available in my CSS file so I'll be just be saving this so let's go ahead and see if it works fine and currently that posting is not visible posting text and if I click on it you can see there is a posting visible and once the data is saved it gone so if I click again you can we will see that right inside the button all right thank you so much for watching my video that's pretty much it and make sure you subscribe my channel it really encouraged me for creating more new videos for you guys don't forget to like my video and share it with your friends see you in the next video
Info
Channel: Programming with Umair
Views: 4,558
Rating: undefined out of 5
Keywords: server actions in next js, server actions in next 13, server actions in nextjs 13, everything about server actions, mutate data in nextjs 13, revalidate data in nextjs 13, server actions forms in nextjs, data mutation, nextjs 13, nextjs, next js, mongodb nextjs 13, mongoose nextjs 13, connect mongodb in nextjs 13, create mongoose schema in nextjs 13, mongodb, mongoose, schema, next.js, light and dark mode nextjs 13, useEffect in react, react js hooks
Id: _0-RcunodFI
Channel Id: undefined
Length: 25min 15sec (1515 seconds)
Published: Sat Jul 15 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.