Build a Next.js 14 Full Stack User CRUD With Routing & Server JSON API Using MongoDB in Javascript

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
uh hello guys welcome to this video so in this video we will be looking at how to build out a full stack NEX js14 user cred application in the browser using JavaScript and Tailwind CSS and you can actually see the live demo on the screen guys we are actually running this application on Local Host 3000 and currently we have one user out there which we are displaying it from mongod DB database we have the functionality for creating user displaying users or updating the information or deleting them so we have the username email address and now if I want to create a new username if I show you the database right here this is my database next cred project we have a table of collection of user and we have this one record which is available which is ID is the primary key name email address and password so we are actually can create a new user and if I click the button create user here I can provide the name and then the email address and here we can provide the password as well click on Create and now your second record will be created and instantly without uh any delay you will see the result as well so if I just refresh my database and show to you just refresh you'll see the second record is added in the mongodb database and we are simply showing that right in the front end as well so we I will be showing you in this tutorial guys uh the data fetching how we do in next year's 14 the API routes all this will be coming in this video we can even edit this information if I click the edit button you will able to edit a particular user and this is actually the API route Local Host 3000 edit followed by the primary key which is the ID this is dynamic routes in nextg and here you can change the username click on update and now you can see your username is simply updated and if I show you the database as well if I just refresh my username is also updated as well we can even click the delete button right here if you want to delete a certain entry you will see are you sure you want to delete Sanjay I will say simply delete and it will make that delete request and instantly that will be removed and if I show you refresh it that entry is removed right here there is a single record available we can create delete update and we can show users so in this way in next js4 we are using Tailwind CSS for the UI that you are seeing right here user interface so if you are interested in watching this video please hit that like button subscribe the channel and if you're interested in purchasing the full source code with with directory structure and full documentation and support from me the link is given you can go to my website pro.com the link is given in the description of the video after you purchase it you will be redirected to Google Drive where you will be having this uh ZIP file which will contain all this directory structure with the full documentation on support I will provide you if you face any problem so the source code is given in the description so now let's get started guys by building this application so we are using next chair I already told you guys at the recording of this video at the time of recording this video the latest version is 14 version and we are using this we are actually using mongodb and for interacting with mongodb we will be using Mongo's package which allows you to actually interact with mongod DB database create collections insert data delete data update data so 2 million weekly downloads and we are using Tailwind CSS which is a user interface for building user interfaces a setad of predefined CSS classes it has and then we are also using S SWR which is a data fetching library for react cheers so it's a react hook library for remote data fetching so we also will using this package as well so let's start building this guys so the very first thing I will do I will simply go into my projects directory and uh I will simply make a new project now to make that project the command is npx create next app at theate latest so we are installing the latest version so next JS user crud project this is actually the name of the project that I'm giving right here this is npx create next app at theate latest so just enter it it will ask you some questions that you want to answer it while setting the next js14 application so it will actually ask you whether you want to set up the source directory you want to use typescript or not so I will say no I will stick to the default option I want to use JavaScript es lint I don't want to use it so no Tailwind CSS I will say yes I want to use Tailwind CSS so simply press yes it will set up automatically for you would you like to use the source directory I will say yes because I do need to use the source directory an app router by default yes recommended so would you like to customize the default import allies I will say no stick to the default options so don't change any option so now it will install all the packages which are required for this so this will hardly Take 5 to 10 seconds depending upon your internet connection so once it is in set up we can open this project inside vs code so just wait for the command to finish so it is also installing those Dev dependencies if you see this is Tailwind CSS this is post CSS so it is automatically setting setting up the tment CSS for you so you don't need to manually do it so that's the advantage of using these questions so depending upon your preference you can use any UI framework so so once it is installed we will open the project in the VSS code so now it is created that next project I will CD into nextjs user crud and open it inside my VSS code this is actually the basic structure of a next 14 project guys we have the app router folder in the source directory we do have the app folder right here if you see in the source directory we do have the app folder inside the app folder we have the layout file we have the index page.js by default every route that you create index every client route that you create you must name your file as page.js right here so if I just start my nextjs application by running npm runev this will start the development server on Local Host 3000 so this is my layout file where you can actually provide your title and description and your head tag this is Global for your application this is the app route here you can write our API routes or client routes as you know and nextjs is a full stack application you can write client side code and as well as server site code you don't need any nodejs or Express so if I just navigate to Local Host 3000 it will just compile your application and it will take some time whether you're running it for the very first time after it it will refresh it you will see this is the next CH basic app and now we can edit this file right here we can remove everything from here we don't need this so we can remove this and just have a Hello World message so just refresh now there will be this hello world message all the styling will be be removed you will see that so in this way now to set up your Tailwind CSS guys you do need to actually you have see basically it created this Tailwind config.js file in the root directory and inside this it automatically done this so now inside your Global CSS file I think this file is not present you do need to create this file okay I think you do need to create this file if you see in the package.json file we have these packages installed which is post CSS and Tailwind CSS and we also need to install this package as well in order to set up Tailwind CSS so just execute this command which is npm install D for a Dev dependency we need to install this Auto prefixer package so we already have installed this tailwind and post cxs so just need to install this that's all and just here inside your root directory in the source directory you do need to create a file called AS Global global. CSS it is saying that it already exist oh sorry it already exists so you will see it has has already Tailwind it has already included that so so you don't need to set up anything so it already automatically did that for you whenever you answered that question so now in the layout. JS file you can see at the very top we are including This Global CSS right here globally inside of our application so that's why it is included now we can actually give any Tailwind class right here to this element so so there is actually a class in Tailwind which you can give which is uh BG red 500 so you need to restart your server npm run def so you can give any tailin class now to your GSX so you'll see the background color will change to red so we will look at later on the CSS part for the time being we just need to set up the mongodb database so we are using this special software mongodb Compass which allows you to actually create your collections and tables mongodb Compass just search on Google and install this software it's a GUI based software for mongodb completely free so once you install this uh you just need to it will look something like this so basic uh this is a connection string DB Local Host 27017 this is a connection string by default it runs on this port number and right here inside your nextjs application you just need to create a EnV file and right here just write this connection string so just say mongodb URI and just write this connection string mongodb colon sl/ localhost 27017 followed by your database name so I will create this database next crud or I can say coding s sorry free media tools this is the name of the my channel right here so I will create this database free media tools so first of all connect it and now simply create this database free media tools I think you don't need to create the database manually this next CH will automatically create it so you just need to provide the UR this full URL alongside with your database name you don't need to manually create the database it will automatically get created so NV file is created now right in the source folder you need to create a lib folder where we will be creating this mongodb dogs file so here we'll be writing our we'll be importing the Mongoose library from the Mongoose package and I think we haven't installed the Mongoose package if you see okay we haven't installed it we do need to install it npmi and S SWR for data fetching these two modules are necessary simply install this npm and S SWR simply install the them and this will be our dependency so it will get added right here in this section you can see that we are using the latest version of everything react 18 next 14 so it is these two packages are added and S SWR so right here uh we need to import the mongoose package from the package and right here we need to specify the connection string so mongodb URI and this will be coming from the environment variable process. EnV and mongodb urri and here we'll simply compare that if mongodb URI is not set then in that case we'll be throwing a new error to the user that uh please define the mongod DB URI EnV variable inside EnV file like this so that's all after this if the variable is defined in that case we will say global. mongus and then if this is not find then we will say cast is equal to Global is equal to connection null and promise null so what what we are doing right here basically Global do is actually a connection variable we are storing it inside the scatch variable so we are simply checking in the safe condition if this scatch variable doesn't have a value in that case we are defining it to global. mongus and here we are defining the connection to be null and the promise to be null and then we have we will Define a function which will actually connect the DB database connection method so this will be a simple async function and here we will again say if cat do connection so this see this means that if the connection already exist in the cat then return that connection cat. connection if if the connection is not available in that case we do need to connect it so if catched do promise then we need to define the options right here buffer commands to fall this is slightly complicated guys you just need to copy paste whatever whatever I'm doing right here this is just to actually connect the database so this is not equal to the just colon right here after we Define the options we just need to say catch. promise and then this have the connect method to actually connect to that database mongodb URI and pass the options as well so this will actually return a promise we'll return this uh Mongo's uh variable you can see that so we have the connect method inside to actually connect to that database then it will return a promise which will have this connection variable so we are simply returning it so after we do this we basically will store this variable cash. connection dash. promise and then we will return this cash. connection and then you just simply export this file so that we can use it in different files export default DB connect so we are only exporting this function right here that we defined DB connect so we are exporting it so that we can use it in different files so similarly we need to create a new folder right here which is models so here models represent the data which we want to store it inside the table so just create a user.js and we now here in this file we will Define the schema or data what we will be storing it again you'll using the package and right here we will Define the user schema so new schema so don't need this so in the schema we have three variables name will be of type uh string and it will be required so required to be true Boolean parameter so name is required then email again type will be of string and it will be required to be true and one other property we are adding is is unique so the email should be unique it can't be the same two emails can't be the same it should be unique and then the password so in this easy way you can Define your schema whatever data that you want to store it in which structure required to be true so we can have more restrictions such as that let's suppose if you want to have a password of certain limit minimum length maximum length you can read the Mongo's documentation it has a very filters available so after you do this we can actually export this export default do models. user and it will actually create this uh model based upon the schema we will name this model as user user schema like this so this this simply means that using the schema that we defined just create a table or mod um just collection inside the database so once you run your application it will actually let me run npm run Dev it will actually create your collection now we need to guys in the next step we need to create our a in we need to just edit this page. jsx to actually retrieve everything anything which is present in the database and show some routes so we will do be doing it in the next section uh now guys we will be first of all be looking at the API routes in next year 14 how to actually create a backend API route in next year 14 so we will be retrieving the data right here which is present right here in this table we have the database we have the table already created user and already two records are present so I will be showing you how to actually create a backend API route to next year 14 this is really easy we have the source folder and we have the app folder right here this is the app router so inside this app folder you need to create a special folder which is API which is specifically assigned for creating API route so just create right here the API folder and right inside this API folder that you see the API folder is created we will be creating whichever uh API structure you want so I will be creating user I want to I am working with user so that's why I will call this as a/ API SL users I will create a brand new folder right here users so right here now every route that you every API route that you create in next js14 needs to be as route. JS so this is mandatory every client out route must be named as page. jsx and every client every serers side route must be named as route. JS the structure will look something like this Local Host 3,000 API users and then here in this we will be creating route. JS so you will see we have created the API folder inside that we have created user folder and then here we have our route file this is the actual structure so right here we have our we'll make this export asyn function and this will be a get request simply so we have this uh basic get function available to us which have request and response this is provided by nextjs inside your route. JS file for every method we have a special method so for the Post method we will look something like this we will write here post like this so for every method we have a function so for get method here we can return anything to the user let's suppose you want to return the response you can simply return return new response json. stringify and then here we can say message to be hello world so this is our API route so if I navigate to so our Local Host 3,000 so this is the client side side here if you open Local Host 3,000 so this is actually opening right here this is a client site if I want to go to the server site I will say/ API slash users so/ API SL user so it is saying some error is there which is uh reporting Observer is not defined uh let me check guys what is error uh guys you can see I have made a very silly mistake right here instead of writing uh response we return reporting Observer that's why it was creating problem and you were seeing this MCH message that reporting Observer is not defined here we need to write the response right here just return we need to return the response and here we returning a Json property message hello world if I navigate to Local Host 3000 this is our client side if I you will see that it is our client site if I want to go to the API route SL API SL user so you will basically see this is our API route that we created a very simple route which contains a message hello world this is a property so in this way you can create both client and server site in next CH now what we need to do we need to actually uh make a route where we can actually get all the users which are present in the database first of all we need to DB connect we need to Simply take this from this uh Li folder which is located in the mongod DB and then we need to import the user as well from models and slash user so we do need the D connection and the user model as well just make your EnV file uh the database right here which we are working right here which already contains some data next crud project just change this and I will change this this to next C project this is my database so so already there is a user table which is available so right here what I will do I will simply make a function export Asing function get and right here first of all we will make the connection to the database we will say await DB connect we will call this function and then in the TR catch block we will basically fetch all the users from the database so right here we will say let users uh are await user and it contains this function find it will actually find out all the users just pass an empty object right here and then here we need to return a API response json. stringify with success you will put a success property and also data property which will be the number of users which are present right here if you just refresh right here just refresh your database it is saying to that catch is not defined so basically guys the link is given to the full source code I have given so you can go to the description and I think I made some kind of mistake right here so what I will do I will simply go to the Leb folder and go to mongodb and paste it the correct code so now if I refresh now there will be no error it is you can see it is compiled if I you will see that two users are there Local Host 3000 API users So currently if you see in the database we have two users so we are actually returning those two users from this API route we have the ID primary key name email password this is also so now this AP route is ready guys now we can consume this AP route inside our front end so in this way you can easily create your API routes inside next chairs and uh now in the next section we will be consuming this route and displaying these entries in the front end using Tailwind CSS so now guys in this section we will be retrieving all the details from this API route that we created in the last section in the homepage of the application so just you need to navigate to The Source folder and you need to go to the page.js file right here and here we need to edit this file so if I just check now it is actually showing uh if I go to it it is it is showing this hello world message instead of this we need to edit this and remove everything from here and just first of all make sure that we explicitly said that this is a client side component in next js14 you need to set this using this use client directive at the very top so this signifies that this is actual client side component and uh we do need to make sure sure that it's mandatory after we do this we do need to create uh a just change this to user this is a user component here we showing the list of users so just change it so after this guys what we will say we will Define some state so we will be defining the data which will be coming and the error if any sort of error take place for this we will be using this hook which is used s SWR it will be imported from this s SWR so it is static validate library in react hook Library which makes it very much easy to actually retrieve data from the API route so we will say the location / API SL users and then we will assign this function which is fetcher so we need to Define this function right here it will actually take the URL and now you'll use the fetch API which is built in you need not have to install any package here we'll be simply going to this URL and this will actually return a promise to us dot then and here we need to Simply return the response. Json property that's all sorry you can directly do this response. Json or what we can do we can say return response. Json that's all so we defined a function we basically using use as WRR where we provide the URL to fetch so we will be fetching from this uh URL and uh this will be coming it will automatically set the state in this data variable or if any sort of error take place then it will show you this error so right here after this we will simply say that if any sort of error take place in that case we need to say a diff fail to load and if any sort of data is not present in that case also you will say loading this is very much necessary if you have a lot of data coming then you can show a loading bar as well so it is a very good package it allows you to set this automatically so we we need not have to use use state or use effect so it basically reduces the boiler plate code and it's a very good dependency aswr and after that you do this we need to assign these Tailwind classes right here Flex right in the jsx class name Flex justify Center just make it in the center and uh then we have another diff Max W3 XEL these are all tailin classes E4 for padding BG white stands for background white then we can even provide a shadow as well Shadow on medium devices MD and round it on large devices and then we will have a H1 tag which will actually show to the user that create user so if you just refresh now let me just show you if it is working as not it is saying object is not iterable uh use S SWR importing we are importing this what is this error use WRR SL API SL users let me just restart it and just check uh again it is saying object is not a trable cannot read property let me see guys what is error uh now guys I just need to figure out the two issues which are happening so basically what we are using this used s WRR I just wanted to show you you can you may also encounter the same issue this will actually return a object right here not array just make this curly bracket not square bracket it will actually contains these two properties the data or error the second mistake that we did is actually we don't need to return this Json from here we need to return this full function this return full function so how we can do that we can either write like this like this we can write this I think it should work compiled we will now see it is now perfectly working so it it simply means the same thing we are returning this full function fetch function to this hook or we can write it in a cleaner way just writing on a single line so this also means the same thing we don't need to explicitly write the return statement so this will also means the same thing we are returning this whole function to this hook it would contain these two properties in the object data or error so now this will be working now to show this uh this data and first of all if you see this uh gray color that is happening the these are the default styles of next CH just go to your global. CSS apart from this delete everything we don't need the default styling so I will simply delete everything and now if you refresh you will not see any default styling so this is the thing just make these slight modifications and now you can actually get your data so now inside the H1 we need to give some classes to it font we need to bold it margin bottom for text Center so if you do this it will give just add this in the center of the screen so this is actual heading and now we also need to have the link tag which will be imported from the next package and it contains the link and this is a link tag guys here we can actually create a anchor tag so you can say create user and I think this was user not create user sorry and now we can actually provide a href property so whenever you click this it will navigate you to the slash create route which we haven't created and right here we need to give some classes to it of BG blue these are all tailent classes right here BG blue 500 and when we hover onto this BG blue 700 and the color of the hyperlink will be in white color and uh font will be bold so if you just make these changes and just see the Local Host Street hous you will actually see this will look something like this and also you need to make it in the centers of the screen so padding we also need to give py2 PX4 from the X Direction and it will be rounded block margin bottom for text Center so you will see the button will be created in background color will be blue and everything is styled so if you just click this button this will show you this 404 error because the the page is not found we haven't created this route in the next section I will show you how to create these client side routes in next year 40 so now we just need to after this we need to show this information from the database so after this uh link we will have a unordered list tag and inside this we will use the map operator data dot so if you see the structure of the API route if you see we are returning the data property from here we can even directly return it the users so if you directly return if I show you Local Host API / users we will have directly our users property which will be a simple array so we can simply Loop through this array so we can simply write here data. user do map so inside this we will have our key parameter which we need to set which will be user uncore ID which is a primary key of the table and then here we can actually show the name of the user the email address so inside double curly curly bracket user. name user. email so if you go to Local Host 3,000 so we will see two records are there we are simply printing these out so we can now style this we can give some classes to it PG gray 100 rounded and these paragraphs will also have classes phone Bol so it will look something like this you will see this is a first record second record and then we have two buttons for actually uh updating the user or deleting them so we will have a div tag right here we have again we'll be using the link tag this label of this will be edit so if you just go to this edit HF property will be we'll not be having this HF now I will show you a dynamic routes later on whenever we do it so for the time being we'll just add these classes margin top to justify Center and similarly we will have the delete button as well so you just need to give these classes to it text blue 500 and for the delete button we will have the red button text red five 100 so this will be there in the same diff tag so we don't need the separate diff tag so just after this you can paste it hrf expects a string or object for the time being we can just say sledit we will now see so the UI is uh almost ready guys this is actually the UI which would look something like this if you click edit it will go to this route we will have Dynamic routes for these function functionality but later on we will do it so the UI is completely ready now in the next section I will show you how to create these routes for creating user updating or deleting user so our we are successfully showing the users from the database whenever you go to the homepage so we'll be showing you in the next section how to create a brand new user uh for the time being guys I can just say right here uh this for the edit and the delete button we can directly do right here because we have the user ID so that Dynamic routes is very simple in next CHS we write qu bracket and then we can write this Dynamic route SL edit and Then followed by the user ID so we'll say user uncore ID like this and similarly for the delete operation as well we will be using that ID parameter in K bracket SL delete SL user do underscore ID so this is dynamic routes because we are passing the ID of the user in both these routes if you refresh now click on the edit button it will actually take the user ID you'll see the ID of the user in this route similarly in the delete request as well you'll see/ delete so now in the next section we will look at how to create a brand new user so now in this section guys we will be looking at how to create a simple form by which we allow the user to create a new user right here in the source directory just make a new folder for create so this is a client side route so SLC create it will do and then we need to make this page.js file this is mandatory that you name your file as page.js so it's a client side route that we are creating client side page just need to mention explicitly use client at the very top and then here we need to it will be a simple functional component and uh you can simply make this as create user so right here uh we need to set some state for this component so we need to say the name for setting the name so we'll use here UST state it will be imported directly so current value will be nothing and similarly for the email as well email set email use State nothing and for the password as well so these three things you will be setting or creating it like this and we do need the router as well for actually redirecting the user when they are actually created your record so now to redirect them to A Different Page we will actually use the use router hook use router hook which is available which will be coming from next / router this is a hook and uh now we will route write our jsx so we will have this classes Tailwind classes P4 space y4 this is padding after this we need to have a heading text to excel phone board and here we'll say create user so if you just navigate to slash create it is saying to us that use router next router was not mounted uh let me see where is the problem right here okay you just need to make sure uh it is coming from next SL navigation just make this change not next router next SL navigation you will now see it will go to Local Host 3000 SLC create this is a create user which is coming so after you do this uh 2 XEL sorry so here we will actually have a simple form and we will be giving a class to it of space y4 and we will have this uh input field input element we'll be giving a class name to it so width I will make it full padding PX in the X Direction 3 py2 in the y direction it will have some border as well it will be rounded and focus when we focus this we will remove the outline outline to none when we focus it we will add a border to it of blue color 500 so these are the classes that we are attaching so then what we need to do we also need to attach uh the type parameter so we'll be storing type will be text so the value of this will be name on change so we'll be attaching a event handler to it so whenever the value is changed we'll call calling the hook function set name e. target. value very simple stuff if you studied react you will know everything what I doing right here and placeholder we can attach a simple placeholder we can say enter name so one field is added if you see here you can enter your name so what I can do I can simply copy this repeat it two more times just to save some time and here we can replace set email will be it will be email type will be email enter email this will be password password this will be set password you will say this is a placeholder and you will now see this is actual form here you can write your email and then the password lastly guys we do need a button for this to actually submit so we'll say create user and then we will have the classes which needs to be attached to the button these will be BG background will be blue 500 when we hover onto the button BG blue will be 600 text will be white padding X4 py2 and it will be rounded so we need to attach a onclick listener to this button or we can simply say type is equal to submit that's all we don't need to attach on click here we need to attach a onsubmit to the form element right here so when we submit the form this onsubmit will actually execute a function which I will call it handle submit so we need to now Define this function handle submit this will have this uh e parameter pass to it so we need to first of all prevent the auto submission of the form like this just make this function as asyn as well asynchronously we running this and then we need to Simply make a fetch request await fetch and/ API SL users and right here we will actually be calling a simple post request here you'll Define a simple method to be post and here you'll passing the headers so here we need to Define this header which is content type application SL Json and uh then we need to define the body as well so this will be json. stringy and here we defining two properties name email and password we are passing these three properties in the body of the request while we are making it so then it will actually turn you a promise guys after it is done it will actually return a promise body is done right here it will return you a promise so if response. okay if this is a case then we need to redirect the user to the homepage you can say router do push push to the homepage start Sol so this is all that we need to have now we need to make this post request in this API routes folder SL API SL user go to the route do JS file and right here in this file we do need to make a post request similarly that we did for the get request so I will show you step by step it's very simple so let me now show you so just go to your API folder route. JS file write inside here we will make a post request to add a new user for adding the new user we will simply say export async function post request response first of all we'll connect to the database so we will say DB connect you will say the try catch blog once again so here we will simply say we need to actually create the user we will say user. create function is available in and right here we will say await request. Json so in this way you can actually get the data which you are passing right here in the content type application Json in the body json. stringify we can get this user request or Json so after we get this we can actually return a new response json. stringify success to be true and data will be user and one other property we will be returning right here you can even return uh the headers as well if you want to this is not mandatory but it's a good practice you can just add a status code 2011 and the header as well this is not mandatory but it's a good Pro programming practice to actually return the status code and the content type as well in the header so if any any error is there then also we can return a full response to the user just to tell them that 400 error is there like this success false status 400 headers content type application Json so this is all uh if you now check if you navigate to your application click on create user enter the information let's suppose I enter John John gmail.com and password click on create user so I think it is saying to us if you check your database this entry hasn't been added I think some error has taken place export Asing function post let me see uh I don't need this so user create in the try catch error right here uh let me see just troubleshoot is creating a user let me see if this error if if uh we are getting this uh request or Json and in the create file right here let me see if we are getting this uh name email and password and just don't uh do this don't redirect the user to the homepage just stay in this page so this is the practice that we use to troubleshoot whenever and any error take place so John uh handle submit we are having this on submit let me see what is the problem which is there uh this is the create file and just wait guys let me see what is there uh guys I figured out the error I just made a very silly mistake and if you see in the E do prevent default this D needs to be Capital so just make this SL adjustment D needs to be capital and one more issue in the route. JS file we essentially write in written this console log statement by accident this is actually a asynchronous call right here request. Json it needs to be having await keyword so simply remove this and rerun your application and if I go to Local Host 3000 and go to create user and let's suppose uh I create a user John so now it should create a user so let nothing happens but if you see we have made a request this data is coming you will see it is console logging it and if you check in the database if I refresh now you will now see there will be three records this John entry is also been inserted so what you can now refresh go to this and right here we can redirect the user you can say router. push to the homepage so whenever the request is successful we will redirect the user back to the homepage so if you see now there will be three entries out there now again if I create a new one let's suppose Smith Smith gmail.com click on create user so now there will be four entries Smith entry is also being added so in this way you can uh do it let me delete this alert statement we don't need it so in this way you can create as many users click on this enter the name enter the email address click on create you will see it will create the user and also inside the database as well so you will see now the rest two operations are remaining the delete and the added operation so we'll be looking these operations in the next video uh now guys in this section we will be looking about how to delete a specific user so if you just go to Local Host 3000 we are in the last section we saw how to create a brand new user so if I click the delete button it will redirect me to this page 404 not found and if you see the route Here Local Host 3,000 SL delete followed by this is dynamic so this will be every time different depending upon which user that you select this is called as Dynamic API routes Now to create these Dynamic routes go to your API folder and right here in the users folder we do need to create after this a dynamic parameter which is square brackets so in this case we will be passing the ID parameter you can give anything right here you can give any name but for this purpose I will be giving ID so inside this we need to create our file route. JS this is actually called as Dynamic route so here we need to actually get the information about the specific user which is passed right here so first of all we do need to actually require the DB connect and this will be coming again from this uh lip folder and it is mongod DB and similarly we need to also get the user model from the models folder and inside this we have the file present which is user so after you do this we now need to actually write a method simple method which will actually return the details about a spe specific user using their ID so how we actually get this ID variable we have this object pass here which is called as params you can call it anything this is actually a function right here export async function get and this is actually the param params which will be passed right here so in this case we are passing the ID here so now to get the ID we'll simply say params do id parameters. id so we can console log the ID so if you now hit this route if you just go to this route and check so this is actually a server route that's why we do need to actually create a client side route where we actually call this just just create a new folder delete now and right here just make a file page.js and it will be a client side component for deleting the certain user and here once again we will be using a functional component you can call this as delete user so we need to also write here include the router use router so it will be coming from next navigation package and right here we need to Simply extract the ID so we do this using use params use params is actually a hook which is available inside next navigation so this is we are doing it in the client side component this is actually a server side component to now to get the server side component we use params do ID in the client side we use use PS which is a react hook and again we will be using the same concept which is uh use the same hook use S SWR and write here it actually Returns the object which contains two properties data and error once again we will call the fetch function and here we'll be providing the ID if the ID is defined in that case we will be making this request to/ API SL users and we will pass this ID if the ID is not defined then in that case we will be passing null and then we will be calling this function feter we do need to Define this function at the top so URL we will say fetch it returns a promise so you can see that it's very simple we are using use S S SWR we are passing the ID right here so now we need to actually make this request / API SL users and this one so it will call this route here which is get function and if you check now if you refresh your application click on the delete button and just make sure inside your uh page.js file right right here so here we are simply going to this route slash delete and here we are providing user ID you will see that so we are going to this/ delete we have this page.js file and right here uh we do need to actually show the user a message are you sure you want to delete this user or not so if you just go to this it is compiling it so just wait so again it will be saying uh 404 not found we do need to write the complete file right here so inside your delete uh I think let me paste this file right here oh sorry the error is coming because guys this is a dynamic route as I already told you this is you can see we are passing this dynamically this ID parameter so in the client side also we do need to follow the same practice so right here let me copy this and so in the delete folder that you created you need to create the same fashion you need to create the square brackets ID so this is the dynamic route and right here we need to create page.js so now if you hit this route you will see this delete user and in the command line you will see the ID printed out so this is a server side route which we are getting this ID passed to it so we are getting the same ID in the command line inside our route. GS so after we get this what we need to do uh we need to simply delete this first of all we need to get the information about this user so we will say if the ID is not defined then we need to actually response. status 400 missing ID parameter so if the ID is not defined then we will return this error message so if the ID is defined then we will basically connect to the database and then in the TR cat block we will get information about this user so await user it contains a function in find by ID we pass the ID and then it will return the information so so if the information is not found in that case you can return error message like this json. stringify success to false status 400 headers so if the user is defined in that case if the user is defined in that case we can simply return the response back to the user json. stringify success to true and the data will be the actual user you can directly pass the user not in the data property just directly pass the user and the status property will be 200 and so if any sort of error take place then we can even return this 400 error so this is actually the full function in the server side route we Define this get request now in the client side component in the delete page.js file so you'll be getting either the data or the error now after this we can actually have if condition right here if the error happens in that case we can say fail to load if the data is not return the case loading so right inside the jsx we can actually write the Tailwind classes right here which is padding for space text to Xcel phone bold and and uh we will say delete user and uh it will basically sh say to the user are you show are you sure you want to delete and here we can dynamically put the username so can say data do name so if you just refresh here if you now click the delete button you will see this data property right here so inside data property we have so inside route. JS you will see that inside of this property that you see right here we are returning the user information inside this user property directly so what we can do we can directly think we can directly print out so now you can see that we can access the name property of the user by like this inside curly bracket data. user.name if you now refresh you will see this heading if you are you sure you want to delete this username if I see the if I show you the servers side route here/ API SL users followed by the ID so here this is the actual ID which uniquely identifies a user simply copy this and paste it so this is actually the route that we return if someone goes to this server side route it actually Returns the information inside this Json response and we get user information such as the ID name email password about a specific user so we are simply displaying this right here are you sure you want to delete and after this we will have a simple button so delete button which will be there so we can actually attach all these tail bin classes so the background of the Buttle will be red text will be white padding for py the button will be rounded so if you refresh there will be a button added delete button so if you just go to your homepage of the application click on delete now this view will be showing right here you can try out for any user you can see that this ID parameter will change because this is a dynamic route depending upon which user you select it will change so now the task is very simple when we click this delete button we need to delete this user so apart from that we will also have a cancel button if you want don't want to delete the user so we have the cancel button if you click it you will be redirected back to the homepage so use router function so click you will be redirected back to the homepage so now if I click the delete button I need to delete this so we need to bind on click listener to this button you can call this function as handle delete now we need to Define this function at the very top so this will be a async function just label it async and then here we need to make a simple fetch call to the backend server / API SL users and here we'll be passing the ID of the user in the URL and the method here will be delete and we also need to pass the headers right here which is uh content type application SL Json and so if everything goes okay then in that case this will be true and and we will be redirecting the user back to the homepage router. push this is complete and now we need to go to route. JS and now we need to define a method right here to actually delete the user so this will be very simple right at the bottom you can Define this export asyn function delete request and the params will be passed right here here first of all we need to get the ID which is passed params ID similarly then we need to make the connection to the database DB connect we will call it and then in this TR catch block we need to Simply make this request delete that specific user we can do this using await user dot it has it this method delete one and here we need to pass the ID of the user and _ ID so we'll pass the ID right here so after doing this uh we can simply check in this if condition that if the user is deleted successfully or not if the user is does not get deleted then in that case we can simply return return error message success to false the user get deleted successfully in that case we can return a simple response success property to True like that so that's all this completes the delete operation and if you now refresh your application and go to a certain user click on let's suppose I want to delete this John user click on delete click on now you will see this user is completely gone from the UI and if I show you the database as well if I refresh it only four entries are remaining let's suppose if I also want to delete this also so instantly it deletes it doesn't take any time you will now see now only one user is remaining and if I show you the database as well the table only contains one entry like this so in this way you can delete user create user and also show the list of users which are currently there in the table now the only operation which is remaining is the update operation if I click the edit button similarly the path will be very similar so we will be covering this section in covering this edit feature in the next section uh now guys we'll be looking at how to tackle the edit operation uh in the last section we look at the delete operation if I click edit again it will be a dynamic route ID will be passed in the URL so once again we need to create uh the server or sorry client side component for this we need to create a brand new folder inside the source directory this one for the edit and then create another this will be a dynamic route so square brackets ID which should be passed so inside this once again we'll create page tjs so the file name must be page.js every time and now this will be a client side component so that's why use client and uh you can rename this to edit user and the process will typically Remains the Same Again we need the router package so it will be coming from use router next sln navigation and we again need to extract the ID we'll be using the use params again it will be coming from next navigation and again we will be using the use S SWR to actually data fetching from the server route to actually get the information about the user which we need to update so again we'll make first of all a request to the server route / API SL users first of all we need to pass the ID we need to check whether ID exist so question mark if the ID exist and we will make this request we will pass the ID if the ID doesn't exist we will pass null and we will use this this function fetcher you need to get the information about the user first of all so fetcher pass the URL fetch URL it will actually return a promise so that's all and now it will return on either data or error depending upon whether so so right here we do need to create some State variables because we are updating the name email or password so we'll use the UST State hook for maintaining initial value will be empty email set email so we have declared all these variables State variables name email password so right here we will be using use effect hook as well this hook that that you all know it will only run right here we need to specify the condition it will run if you write here square brackets it will run every time but here we need to specify condition that if the data is returned to us then only execute this right here so if the if the data of the user returns then only execute it so right here if the data executes if the data fetching is done we will be setting the updated name like this dynamically data dot user.name similarly set email to be data do user. email and password to be so this is done because we need to pre-fill the entries of the inside the input field so let's suppose the user hit the edit button that pre fill entries need to be pre-filled that's why we are doing this and after we do this now we can simply write the jsx and also write these if conditions right here if the data is not defined will show a loading bar so this is typically the same uh we return this all this jsx when we created the user so all these classes will be the same so I will not waste time in writing once again this this time this will be for edit user rest of the things remain the same on change placeholder everything Remains the Same The Heading will change from create user to edit user and uh the form Remains the create button will change to update everything will remain the same so if you now click your edit button you will see that uh it is saying handle submit is not defined so just make that function prevent Auto submission of the form so you will see automatically the data will be pre-filled the old values will be pre-filled in the input field now you just need to update them and click the update button so you can do it for anyone you can see that so this is the update operation so now we need to write this uh handle submit function so this is very easy inside handle submit will make a simple fetch call to the backend route await fetch / API slash users and again we will pass the ID in the URL this time the method here will be put because we are updating the information modifying the information and also we need to pass the headers which is and here the body will be again you will be wrapping this with Json stringify we passing the name email password and uh if all things are okay then this will be true response okay and then we'll be redirecting the user to the homepage now this is this file is done so just make this function as async so now you need to go to again your API folder this uh route. GS file and right we Define the get method we Define the delete method in the previous now here we need to Define uh the put method request so right here we need to first of all fetch the ID from params do ID after we get the ID this becomes very much easy to actually update the user using their ID so will be actually be connecting to the database and then this inside try catch we have the function uh which is user dot find by ID and update this is a function provided by mongus provide the ID and then provide the data updated data and then there is an object you need to pass here which is new property you need to set it to true and run validators to be also true so new means that we are updating the data that's why you need to pass this and right here if all goes well and we will simply return the response this is not necessary but just for the clarish we will do it success property to true that's all this completes the this things this thing is not necessary because we are not returning we are not getting some but I'm just writing it for Success message this really is finding my ID and updating it so just wait refresh your let's suppose if you want to change the name of this click on edit and let me change it to my name click on update you will see the name is updated and it is reflecting back here if you also check the database refresh the name will be changed in this way you can create a brand new user you can see you can delete it are you sure you delete it you can edit change the information so you can see that so this is a actual crud application guys we developed in next js14 with routing and navigation so if you like this video please hit that like button subscribe the channel the full source code of this application with directory structure documentation and support is given in the description you can directly purchase it from my website proc Cod store.com so thank you very much for watching this video video please hit that like button subscribe the channel and I will be seeing you in the next video
Info
Channel: freemediatools
Views: 224
Rating: undefined out of 5
Keywords: freemediatools
Id: eallarJ1qbE
Channel Id: undefined
Length: 92min 29sec (5549 seconds)
Published: Mon Jul 08 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.