Nike App Backend: node.js, MongoDB, Redux Toolkit Query

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's up no Jazz developers welcome back to a new live build and today we have an exciting project today we're gonna build the back end up back-end application for the nicap we're gonna build a rest API using node.js Express mongodb and we're gonna query everything with Redux toolkit from out from the front-end side in our react native application so it's a build full of new technologies and uh I'm super excited about this and I hope you'll learn a lot today this is a great tutorial for not specifically Nike application but any Commerce application that you might be building so if you have some a project on the side or you have some ideas take this as an inspiration follow along and learn how to structure everything and how to put everything together in order to have a fully working end-to-end application so um what exactly we're going to do today we're gonna start by building the rest API and we're gonna do that using node.js and express for the database layer we're going to use mongodb which is a nosql database very popular out there and with these tools and Technologies we're gonna build all the crude operation like create read update for our models and the models will be orders will be products so that the user can query all the products can add them to the card and in Van can create orders and then track the orders in the application so um after that in the second part of the tutorial also in this video we're gonna query all of this data from our react native application and we're gonna do that using the Redux toolkit query um yep that is the plan I hope you are as excited as I am uh and if you're new here hi my name is Vadim I'm a full stack developer I've been working at multiple companies including Amazon I've been co-founding startups but now my passion is helping you build end-to-end impactful applications so if you enjoy what I'm doing here make sure to subscribe to the channel and grab a cup of coffee because we are up for a great build today before we get started make sure to download the asset bundle at assets.nojas.dev Nike because that will include some dummy data and some pre-made components that I have prepared for you in order to speed up the process of following along and if you already downloaded it uh before then try to do it again because I included some updated files specifically for today's tutorial as well I have prepared for you a step-by-step guide with code Snippets in order to make sure that everyone can follow along and you can compare the code with them with a guide so to access it make sure to go uh check them in the description of a YouTube video below I included the link to that step-by-step guide let me actually find because I will also need it uh just give me one second here it should be and is it like this come on yeah if you go here under the follow the step-by-step guide under this video You're Gonna Be redirected to our not just.dev website where I have all the actual steps that you have to do in order to follow this tutorial don't worry we're gonna take it step by step I'm gonna do everything together in this live stream so there is not going to be a lot of copy pasting without me explaining what we actually do because I'm trying to make sure that everyone actually understands what we are doing rather than basically copy and pasting because that's how you learn and can apply the same knowledge to your own projects so uh I wanted yeah before we jump into uh the building project I want to say hello everyone in the live chat how are you doing guys I see a lot of people today are joining us a lot of you have been asking for and no Jazz backend and here we have it uh you ask we provide is it from a single stream wait a second let me see hi guys hello please hello guruvir how are you doing guys ignas Rocky David I want to remind everyone that uh if you're watching this live you still have opportunity to join our giveaway that we are organizing we're organizing this giveaway because I lost a bat in one of my previous live stream where I didn't manage to build an application in one hour using flutter what a shame so yeah I promised there to to do a giveaway actually I promised here to do a giveaway for 50 discount for uh for my premium course but we fought with a team I decided to do a full uh like free entry for one person for the premium course so you can enter it by going to ss.nodes.dev giveaway and you have opportunity to win one place uh in our inside our premium course that you can find at Academy dot not just the dev and actually I have previous week we have launched a new module inside our course all about notification including enough notification education push notifications with Firebase Cloud messaging so yeah the course is getting bigger our community is getting bigger a lot of people enjoy it and are taking actual value out of it uh with that being said yeah join the giveaway you might be the one who will win it we're gonna announce the winners uh at the beginning of the next week so you still have a bit of time perfect um I think we are done with a presentation and um I think we should get started because we have a lot of things to learn and to build today let's go ahead and open the step-by-step guide I'm gonna do that as well and we're gonna start following along the steps that we have prepared there so let's scroll a bit until we start with node.js server so I forgot what we have to do is to Simply create an empty directory uh so for that I'm gonna um I can do it here but let me just simply open the director with my project to better okay it should be here Nike so yes in in it um let's start by creating a directory for our backend application let's create a folder and that's going to be Nike up backend now we can go ahead and open this application in Visual Studio code let me open it like this okay Nike application backend here we have it and initially we do not have anything there because it's an empty directory so what we have to do is let's go ahead and initialize an npm package that will be the base of our of our node.js backend so for that let's go ahead and do npm init and then slash y to accept all the defaults and what that does is it created webpackage.json inside our project and now we can add dependencies we can run this project and so on speaking about web dependencies uh let's go ahead and install the first dependencies but we will need um I'm going to start by installing uh a Dev dependency which is called node Mon and this dependency will help us run the server and not simply run it but watch our files and every time we do some changes it will restart automatically with server so we basically have some kind of a hot refresh that we get in react native but it's very useful because we will do a lot of changes and we don't want to stop and restart the server manually that's going to happen automatically by node one and once we've done that I think we can already add a script inside our package.json that will run our project and the script is going to be called Dev so every time we run npm run Dev what we want to do is using the node mode we want to execute them entry point like we execute the file that is going to be the main file of our application so let's do index.js um but we do not have this index.js yet so we're gonna get there we're gonna install it because for the index.js we need another dependency and here I'm talking about the Express package and let's go ahead and install npmi Express and express is gonna allow us to easier handle and build our rest API inside the node.js basically we can do everything without Express but that's gonna require a lot more code to write so Express simplifies uh creating managing and running the server so now that we have Express installed uh we can go ahead and create our uh index file that is going to be the entry point of our backend application for that I'd like to structure all my source code in a folder called SRC so let's go ahead and create that and inside it let's create the index.js okay perfect so here in the index.js we're gonna need them to import Express using require let me actually probably Zoom it more so yeah require Express Now using Express we can initialize our application so let's do const up equal Express but it's gonna be the instance of our application and in order to run this application what we have to do is we need to call up Dot listen we need to provide here a port uh on what what port to listen so for example 3000 and then we kind of provide a callback function that is going to be executed when the application has uh run so what I'm going to do here I'm gonna simply console log something so we see in the uh in the logs that yeah the application is indeed listening to incoming requests so API is listening on Port and what I'm gonna do is actually I'm gonna extract this port into a variable because that's uh that this port is usually coming from an environment variable in order to be able to um to adjust it on the go on different environments basically in production you can have a different port in development you you can define a different port so let's listen to this port that we Define on top and lastly here the port like this okay perfect this is a very minimal uh API that will not do anything but let's go ahead and try to actually run it so we're gonna execute the npm Run Dev because if you remember we have added the script here in the package.json the dev that will execute node mode on the source index.js so if I do that we should execute node mode as we can see here source index.js and we see that our API is listening on Port 3000 okay that's good but at the moment nothing will happen so what we have to do is we have to uh to specify some endpoints and what should happen when we access both endpoints so for that demo purposes like everything starts with a Hello World let's go ahead and display the hello world whenever we access them uh the main endpoint layer so for that we're gonna use the up Dot and here we need to specify the method that we want to implement so we're going to implement the get method which is going to uh um I'm going to explain a bit more a bit later what is the difference between get and post but basically uh here what we have to do is to specify the endpoint so we're gonna Implement them request for the root the for the root endpoint and what should happen here in the Callback function we get the request and the response and using the response we can basically send some HTML back to um as their response so if I do HTM H2 hello world and close the H2 here um we do I need to restart it because Norman will automatically restart due to changes and what we can do now is go ahead and access our localhost at Port 3000 and see if everything is working as expected come on where is my window here yeah so let's go ahead and access localhost double dot 3000 and what we should see is the hello world here because that's what we return as the response all right so that's um the first step we have a basically running node.js backend uh very very minimalistic but we um we have it ready to implement our crude operations for the next part before we do that let me just double check the comments if everyone is able to to get started if we are all on the same page hello Gerald Joshua hello Vladimir from Serbia hello how do you register for the giveaway again so Joshua what you have to do is um where is my presentation uh go to the assets dot not just dot Dev slash giveaway uh in there you can enter the giveaway by leaving your email and we're going to choose one random person for from everyone who joined sloth hello everything is working so far perfect all right um so back in our guide here our next step yeah we are done with setting up a node.js server so we can scroll down a bit here you can see all the code that we wrote and that I have explained uh and now we get to the product screwed okay so uh what we're gonna do now is we're gonna start implementing some logic that will handle them um that will handle your products let me do this um when you're building a backend it is a good recommendation to split the concerns into different layers and this will help ensure that your project is going to scale easily because when you get started yes you can do everything in the same file you can do everything at the same level and it's gonna be okay but once the application grows and if you suspect that your application is going to be huge in the end then it is a good recommendation to start from the beginning from with splitting everything into different concerns so these concerns starts from the top and the first step is a router and the router basically uh redirects the traffic to the right controllers so basically if we're going to slash products the router will say okay we are dealing with products I'm gonna give it to the controller product if we're going to go to slash orders that's gonna redirect to the worders when the controllers will handle all the HTTP logic and we're gonna get there I just wanted to introduce the router and let's now go ahead and see how we can Define this router with Express uh so for that uh we're going to go into the source and let's create a folder for our router so router here we have it in the router we're gonna specify different files for different routes of our application so because we started with the product screwed let's go ahead and find the product router.js okay so uh we're gonna start by importing Express from Express and we're going to create a router using router using Express dot router come on yeah just like that now in the end what we're gonna do is we're going to export the router so let's do it right now not to forget about this and what is left to do is to define the routes for our products inside this router so it's going to be similar to how we indicated a route here directly on our application basically app.get and here we indicate the path and a callback function only the difference here is that we're going to use the router so router.get well when we try to access the root path of this router and we're going to indicate by slash what we're going to do is we are going to implement the Callback function that will receive the request and response and yeah like we're gonna do response dot send uh get all products um you might expect that well um when we will try to query all the products don't we want to query not very Brown not the root um URL but maybe slash products well that's uh exactly what we're gonna do however this product is going to be part of the whole router so our whole router will start with products and now we need to specify everything that is after that like products.all or products.top 10 maybe you have a specific route so we will delete everything that is before and leave only the parts after them main like products route uh perfect now uh we're going to I haven't introduced you the requirement so if I scroll down a bit the requirements for this rest API I Define them here so for the products we would like to get the list of products because we want to display them all the products in the application and then when we will click on one product in our application we will want to query one specific product by sending the product ID so um regarding web products list of products we have this URL here and regarding getting one specific product we need to implement another get method that will uh contain some data in the URL and that data is going to be a dynamic part of a URL that will represent the product ID so if there will be something after a product slash and some numbers or some letters that's going to be parsed as a product ID and inside our request we're going to have access to this product ID um by yellow let me do rest dot send and here get product with ID and here I can do request.params dot product ID so this product ID is going to be parsed from the URL I'm gonna show you in a moment everything how is connected uh but yeah like for now um we Define two main routes for our products that we will need to get all the products and to get one product by the ID what left for us to do is to connect this product router to our main application inside the index.js so this is our application um yeah to do that we will first have to import the product router product router uh actually in the guy they called it route so I'm going to switch to routes in order to to keep consistent with a guide so product route equal to require router and from their product routes now what we have to do in order to as add this router to our application is to use the app.use and we're gonna say that for all the routes that starts with product s we want to use the product route and now we do not need the hello world if maybe we can leave it just to to have it there so with this uh being added to our project let's go ahead in our browser to the Local Host and E now if I refresh I still should see the hello world because this is the main page but if I do slash products that should say Get Well products and now if I'm gonna do slash product slash one two three that should say get product with id123 um I I know that you cannot really see this product ID here because it's too small but yeah um it's just localhost with report 3000 slash products slash one two three now what that how everything was connected is our app um will redirect all the requests that are starting with Slash products to the product routes and now the product routes is our router that will handle it basically it varies something after products then that something is going to be handled as a product ID and it will automatically be parsed and if there is nothing there van is going to be uh handled by our get wall products uh callback here okay so um yeah for now we are good with a router The Next Step will be to um actually integrate with our database and return some products from the database if we go to our guide for the database here we have it as I said we're going to use mongodb for the database which is a nosql database and it's really easy to work with it it's really flexible we do not need to have a strict schema for our data and yeah that's going to help us a lot in today's tutorial we can run a mongodb locally but in order to avoid all of the struggles on installing and setting up mongodb locally what I decided to do is to go with them mongodb Atlas basically you can launch a mongodb instance on their website just follow their mongodb.com and here let's go to create an account it's free I'm gonna sign in here command and we have we offer free database clusters for specifically development and for Learning and playing around with mongodb uh all right so in our Atlas here um in my case I have some projects maybe you do not have any project and what we have to do is we will start by creating a new project uh let's go ahead and give it a name so Nike up I'm gonna do next four event members and set permissions I'm okay with only myself here and let's press create project okay the project has been created and the next step is to actually create a database so let's go go ahead and press on this button build a database and that will ask us to select what type of database so here in the last option we have a free database make sure to select this one unless you don't want to yeah like be charged it's going to be enough for the purposes of this tutorial and we can leave everything as it is and just press create in The Next Step what we have to do is we have to create a user here so I'm gonna go ahead and write Vadim and I'm gonna Auto generate the password and make sure to copy this password and save it somewhere uh save uh but save it now because we will need it in a in a few moments so you will you will need this password in order to connect to our database we'll also be able to delete and create a new user where we set the password but it's going to be easier if you just copy this user password and let's press create user so everything was created perfect and in the Second Step here we ask us where would you like us to connect from and uh yeah what we have to do is here we have to whitelist our IP so I'm gonna press on add my current IP address and that will automatically add my IP address and whitelist it in order for us to be able to connect from our local environment to our mongodb database so let's click click finish and close and go to database okay we have it perfect we can open it here and our collections which are similar to database tables uh will be displayed here under the collections so do we have to add data now let me see how I prepared everything yes in order for us to start with some data and see some data whenever we query it I have prepared in the asset bundle if you go to the asset bundle give me just one second in the asset bundle here go ahead and open the code directory then data then here I have prepared a file called products.json not product.js because battles for the first video it's product.json so what we have to do is just simply open it in in any editor I'm going to open it in Visual Studio code why did you open in a new window I don't know open and this contains data about our products in a format that is going to be added to the mongodb so let's copy everything from here go back to our collection tab inside our cluster I'm gonna show you once again how you can get here so from from the mongodb atlas go to the database here you should see uh the select the project if it's not selected already from this drop down and you should see the cluster go ahead and click on the cluster inside the collections what we have to do is we have to press on the add my own data so for the database name let's go with a test and for the collection name I'm gonna call them products okay after inputting test and products here let's go ahead and click create that will create our collection and what we should do is now we can go ahead and press on the insert document here that allows us to insert documents this is a visual form of inserting the document so let's switch to vet Json form by pressing on these switch here in the view as Json with curly brackets and let's delete everything from here paste the code that we copied from the product.json from the asset bundle and once that is done we can press on the insert we'll wait a couple of seconds and then our database will have 16 products there so we already can see them the mongodb automatically generated uh unique IDs for all of our objects and yeah like we can see that yeah like we have images we have sizes descriptions and so on everything that our application will need perfect oh why did they open Spotify did you use Mongoose no I haven't used Mongols I interacted with mongodb um like directly just to keep things seem easier foreign are you using any paid Services what do you mean by that in this build this build no everything is open source and the only service that we are using is mongodb which they have a free tier and yeah they're not sponsoring me for doing this it's just my preference for hosting easy mongodb table specifically for development all right so now I hope that you have um managed to follow along till now uh is anyone following a long long life and if yes can you please let me know if you managed to import the data and if you have everything working so we can move on hello pranav how are you doing why not SQL um I don't know it's my personal preference to work with mongodb whenever working in node.js I know both grass says ql is gaining a lot of traction lately so that's also a very good solution don't have anything against at the end of the day like um choosing between a nosql and SQL database it depends on the projects that you're building and seeing what works best for that specific project but both are really powerful database systems foreign thank you can you make this up in AWS amplify we will do a lot of our application in AWS amplify and we have a lot of application in AWS amplify I like that the situation when I'm doing something in AWS amplify and everyone is like hey can you do something with node.js I'm doing something with node.js and everyone hey can you do it with Adobe assemplify so I guess there is there is not there is no gonna be a moment when everyone is satisfied that's for sure Nike Merton project please exactly that's what we have here all right guys all right so um let's let's move on let's move on with our API uh and yes like what do we have to do here well um as I was talking about separating concerns between layers we started with the router layer which is basically the first layer that a request gets to and then we will have our layers that will handle the data will manage everything but the last layer in all our stack is going to be the database layer and this layer is going to be responsible only for interacting with our database reading and writing to database and that's it so let's go ahead and start building our this database layer uh and for that we're going to start by defining a folder in our source called database and I'm going to start with a file here db.gs that is going to be responsible only for making the connection to the database so um yeah to connect to the database from our node.js server we will also need to install a dependency so I'm going to stop the server here and what we have to do is let's go ahead and install mongodb uh version 5.1 so yeah mongodb is going to be the package that will allow us to connect from node.js to mongodb got a problem with a product that it says it has errors make sure uh when you serve a document to delete everything that was already here because if you add it after afterwards then you're gonna have this error so make sure it was the wrong file yeah make sure to open the product.json not to have issues with that can you do this in Super Bass all right guys all right we can do everything only the concern is time so if you have some spare time that you can share with me I'd be happy to take it and do even more tutorials in any tools and technologies that you want I always love learning new stuff as well so there's going to be a win-win situation for everyone so yeah that's a good idea we need to open a bank donation of time send me time guys uh okay okay okay so uh yeah we installed mongodb uh let's go ahead and inside the source database db.jsgs let's go ahead and import client from not from I'm always doing from using require mongodb here we have it the next step is we need the URL uh for to in order to connect to our mongodb so where do we get this URL we can get it from our um mongodb.com from the atlas so let's go here and let's go to the overview uh not even overview right I think we need to go to the database yes just press on the database in the left panel and here under near the cluster zero you should see the connect button if we press on disconnect it will tell us uh basically how to connect and we can choose that we want to connect from our application let's press on this second option connect from our application and here is our URL just copy the URL that it generated for you go ahead and paste it here and one last step is we need to set the password and here is where you need the password that I told you to save uh in some notes I'm going to go ahead and grab it for myself uh here we have it yeah I know you can see it but I'm gonna delete it soon so if for some reason you lost the password uh it's not a big issue because you can go to the database access under security you might want to delete one of the users that you don't you don't know the password for and you can create a new one by going here choosing a password setting my name for yeah um and entering a new password so by doing that uh also you have to add a role for read and write to any database and lastly create add user here and you can connect with a newly created credentials I'm going to delete it now and I'm gonna return to our project okay so we have a URL the last step is to connect our mongodb and get the client by using client uh actually we need to initialize this is a class new client and here we need to send the URI okay that will give us a client that will allow us to communicate with our mongodb database uh so let's go ahead and get that database but we want to interact with and we're going to do that by calling client dot DB and here we're gonna put test because the database name that we created was test if we go to the database here cluster zero and if you go to the collections you see here that we call the test if you call it differently take it from here the name of a database and the products is our collection so the next step is going to be to get our products collection by using the database dot collection and here the name of a collection that again you take it from here test dot products test products all right so now that we have um access to the products collection let's go ahead and Export it from here because we don't want to do any more logic here the purpose of a db.gs was simply to connect to our database and in order to split the code nicely in order to have everything in separate files and easier to manage afterwards we're going to create a new file in our database that is going to be responsible for interacting with a product collection basically create read update and so on so let's go ahead and in the database do products.gs and what we need here is first we need this products collection that we Define here so let's go ahead and import with database from the SE directory database and this database will have a products collection and here we will Define two functions one function for getting all products that is going to be an async function and another one for getting one product this is also going to be a sync and here we will also receive one parameter ID because we need to know the ID of a product that we want to query then what we have to do is we have to export these two mod these two functions using module dot exports and here we're going to export them inside the object let's get all products and get product we need to export this Tool uh because we will need to call them [Music] but yeah before we need we will call them what we're going to do is let's implement the logic of this uh office calls so to get all products what we have to do is we will use the database that we imported here so cost product equal uh we're going to call the DB dot products that our products collection and we're going to use the operation find to basically return all our items here if we don't specify any parameters uh find will return basically all the items and what we have to do with it after we receive them we need to transform them to an array so that's going to be dot to array so lastly let's go ahead and return these products from from a function to be able to use them down them on the road in router regarding the get product um we're going to also use the db.products collection but in this case we're not going to call find but find one and by specifying find one dynamodb will use this filter that we send here and we'll return the first item that matched the condition and how do we want to find basically we can search by the name we can search by the size by a lot of things but what we are interested in is searching by ID all right uh the thing is that if we look at our collection products our um our entries they do not have an ID they have an underscore ID and as you can see this is not a proper string this is a of a type object ID and in short this is only to optimize how dynamodb queries and links everything together but what we have to know is just simply the ID is not a string it's an actual object ID so now what with that being said we need to find one by filtering based on the underscore ID and what we have to filter on basically not this ID here but based on the object ID that we can create with new object ID the subject ID was automatically imported from mongodb and we can pass where the parameter ID to transform from a string to an object ID lastly we can return the product and with our products database layer we are mostly done because we have only one line here we can simplify this by returning right away without saving them to a variable so that's going to be simplified to return touring and you can even remove a weight but but a little bit more advanced okay so we have our database layer and every time we call get all products this will fetch your products from the database and what we have to do next is to somehow connect our router that we have defined in the beginning and the database layer in a real world scenario in between these two layers the router which is the closest to them which is the first layer that the request is past two and the database layer which is basically the last layer in between them there are more layers yes a lot of layers in order to build scalable backends so basically we have a router then the second one is a controller that is responsible for handling HTTP logic uh like adding them headers adding status codes and so on then the controller uses the service layer that is responsible for business logic basically doing all the calculation doing all the checks if if everything is in line with business rules of application and lastly the service layer is using the database layer I hope that didn't confuse you uh and just gave an idea of how everything works and why we have to split everything into multiple layers uh and that's just because to make our project scalable so that at any time we can basically change some of these parts without impacting all the code of our application for example if we want to change the database from a mongodb to a postgres SQL what we have to do is simply update the last layer of the database layer without changing anything before anyways for this specific tutorial we're gonna skip the controller and the service layer just to make everything more simple because we have a quite a simple project so what we're going to do is from the router straight away to the database we are going to integrate them together skipping the controller and the service layer and with that being said let's go ahead and open the router and the product route and here for getting all the products what we have to do is yeah we have to get them to import something from our database layer database and products we will need both get all products and get product function and yeah here inside our first method where we want to get all the products basically we're gonna get them by calling uh get all products and that's it we can go ahead and do console log product and we're gonna see what we have there so I'm gonna go make sure to run our server with npm run Dev and let's go ahead and open localhost slash products simply slash product without slash anything else afterwards that should do something loading loading loading hopefully it didn't throw any errors so it should go here get all products and we don't see any errors but in the console log we already see beta that means that everything was connected correctly and our connection to mongodb was done successfully we have access to it and we get all the results back the last step here in the router layer which actually should be the controller layer I don't want to get to to confuse you too much but yeah in this router layer what we're gonna do is uh for the sand instead of sending a um a string we're going to to respond with um uh Json with a Json object and we're gonna say that yeah like vastatus was okay and the data is going to be product so if I do that and go back now to our browser and refresh we see a list of Json in our case that should be a bit different because I have um tool to um to beautify the Json it might look for you like this it's a bunch of data but this is the data of our products so we see that there are some images there are some sizes here description and so on and if I put in the parse mode you don't you might not have this functionality this is a extension uh yeah we see that the status is okay and we see in the data we have 16 items and all of these items contained by D image name and so on basically the data that is coming from mongodb and we can see that it's actually coming from mongodb if we uh no let me actually implement the second one and the second one is getting one product so here we're gonna do the same product equal a weight and we're gonna use the get product method from our database layer by sending the ID so what's the id but it is this requests.params.product ID and yeah we need to make this function a sync make sure to do that and as a response let's delete this response and send status okay and data product now if I'm going to copy the ID of one of these items and add it uh after the slash here so slash product slash this ID then what we should see is the data of one single um product so basically yeah it's the same ID if I do search this is the one if you're gonna stand something different to this as an ID that will crash your server just because it will try to um it will try to parse this ID that it will try to parse this string that has less character than necessary it will try to parse it inside the products.js here in the database to an object ID and doing that is going to throw an error because the object ID has a very specific structure so it's not going to work like this what we can do is we can add some error handling in order for this not to happen so we can do a try catch inside our router so we're gonna try to get the product here and if we get an error what we're gonna do is we're gonna respond with what we've uh status failed and we can also send an error back with the error itself Additionally you can add HTTP status codes because without adding anything the default status code will be 200 which will represent which will which basically means that everything went okay the thing is that it didn't went okay so what we can do is we can before sending the data we can set the status to a status code so it can be 400 or 401 think 401 should be for bad request if I'm not mistaken now if I'm going to yeah the server should also be failed so you might have to restart it and now if I'm gonna do it like this one more time we see that it's failed there is an error without any actual error I don't know why error Dot message or yeah errorless message says argument passed in must be a string of 12 bytes or a string of 20 okay and yeah now everything works another problem is if we pass an ID event has a correct form but we do not have an item with that ID so it's I will delete one character and we'll add one random character and if I do that we see that it simply what did I land on one correct no let me edit something inside here okay we see that the data is null which means that the ID was correct but we didn't find any products and that is a very common error um basically this is a not found error in that situation uh we have to handle it on this level so we after getting the product from the database layer we can check if product is null that means that we didn't find that that product so what we should do is we can send a response like this with a status code of 404 which stands for not found status failed error message let's do um product not found and also make sure to do return in order to stop the execution here and not send the status okay with that being said now if I'm gonna use an ID that is not in our database what we should see is we should see status failed the status code should be 404 and the error should be not found if everything is working correctly come on yes product not found if I'm gonna open the dev tools and checking the network I'm gonna do it one more time we see that the status code of this request was 404 which means not found amazing but everything with a correct code should still be working as it was working before yeah we see it here all right so um with that being said we are done with web product uh crude operations so what we have done so far is we have starting from the lowest layer in the database we have connected to our mongodb database inside db.gs and we have created a reference to our product collection using this products collection inside database products we have implemented two functions that will help us get the products in the get wall products function and also get a product by ID by calling a specific dynamodb functions like find and find one then this function we are calling them directly in our router so whenever we are doing a request to products then we are using the Getwell products and we send them there I can delete this console log and whenever we do a request to product slash N9 ID we are using bet ID to get the product based on it and we're doing also some error handling to make sure that we handle situations where the product is not found or by ID is not the correct form in a in a correct way if okay um so that's everything we regarding the products that we will Implement in The Next Step we're going to implement the orders uh crude operations uh and for that we're going to implement the creating an order and also getting an order by ID um someone is asking if we have Services product service and orders service and we need to get orders with products does it mean that we need to get data and merge from both services or make one function in one service usually in a rest API um you have you do not merge with data in most of the cases usually you query all the orders and your worders will contain order IDs and then from your client side you will go ahead and for every order you're gonna query the products so in this way you have everything separated that's why actually I love graphql more than the rest API because you can easier create a relationship between data hi I'm Ron how are you I'm doing good if we want to use Firebase can you use it yes you have my permission you can use Firebase will it work on a mobile app yes it is check out Firebase react native package for that I love a key software development paradigmin you are using that's a concept that we should all follow always not only in software development and key stands for keep it simple stupid basically don't over complicate things unless it is necessary and I know a lot of developers suffer from this problem like hey we need that we need that we need all the layer service layer database layer controller layer when you are building like a to-do list application like come on if you know that the project is not going to grow in size keep it simple baby we can always improve we can always update we can always optimize and it's sad that so many projects and side applications and ideas are killed by premature optimization like that that kills so many products like and specifically uh software developers have this problem because we always want to optimize thing we always want to learn new things we heard about a new technology and we think that without that we cannot launch a product now you can you actually can and a lot of people are launching products that have less knowledge when you have so go ahead and build something something great with with the skills and with the tools that you already know and slowly you're gonna add more things to it slowly you're gonna learn stuff new stuff and implement it but don't let that stop you from actually getting something out there a little bit of motivational speak you're welcome will you hand our error status as a message centrally later or will it be in line for every API service try catch uh for this mold project I will not handle them uh centrally and actually like there is not a lot of error handling here like we have basically four endpoints to get product get product by D creating a order and getting worded by the so we're gonna be okay with handling them in line is it possible to install mongodb in server what do you mean by that is it possible to run a mongodb server yes you don't have to use the mongodb.com atlas in order to use mongodb mongodb is open source and you can run it on your own server you can run on your own PC that will work totally fine um yeah and you simply connect the same way as we are connecting now are we done no no no we are not done guys stay here we have still a lot of things to do so let me quickly revisit and for everyone that is just joining uh this video what we are doing now is we are building uh a backend for e-commerce application and we're going to do this based on the Nike application that we started in the previous episodes of this series so for the back end we are building a rest API using node.js and express and for the database we are using mongodb so at the moment we are almost done with building our backend we have implemented the necessary operations for our products like getting all the products getting a product by ID and what is left is to implement uh necessary operations for the orders after that is done we're gonna switch to querying this API inside our react native application so that's also in today's video stay tuned till the end and we're gonna do that using the Redux toolkit query I hope you will enjoy uh always uh all of this build and if you do actually make sure to subscribe to my channel I see from analytics that more than 90 percent of you are watching and you are not subscribed why it's so simple just do a post request on the Subscribe button right now guys okay so as I said we are ready to move to the next step and Implement our worders um yeah like the all the crude operations not all the crude operations to be fair we're not implementing all of them we are only implementing what we need for replication and in our application we need to First create an order and then we're gonna need to track an order so for that we're gonna need to query one order by by some kind of an identifier so let's do just that let's drink some coffee um just a small reminder everything that we are doing is in them step-by-step guide that you can access in the link in the description below so we are done here with our product routes and so on we are ready to start working on the orders um so where do we start from we're going to start from the router so inside our router let's go ahead and create our route for the orders um model so I'm gonna go ahead and create a new file order route dot Js and it's going to be similar to the product route try to pause the video if you're watching it afterwards and try to do it yourself giving give yourself yourself a challenge and try to at least implement the get worder by ID yourself and after you have done that come back and let's do it together that's going to be a great exercise for you to make sure that you can use the knowledge and the concepts that we already wrote adjust them to a different use case and implement it yourself that's basically everything about coding like you don't have to remember you just have to know where to look take some pieces and adjust them based on your needs and understand what what we are doing not simply copying pasting them so after we were done with that let's go ahead and Define our router for rewarders we're gonna need Express for that and let's define the router using Express dot router in the end of this file we're gonna have to export our router so let's do that not to forget to do it later and now we need to define the endpoints for our worders so what will we need we will need a get operator to get the worder um so that getting the worder we're gonna do it based on the difference between a product is that for a product we specify like get product by ID for the Wonders what I plan to do is instead of getting border by ad I want to get the order based on one reference like a small string that we can send to the user on email or an SMS that he can use as a tracking code so that reference is not going to be ID because I don't want to expose IDs to the end users so for that reason uh the get method will work based on a reference and this reference I'm going to show you how we will generate in a moment so request response if you have done it with ID yourself perfectly fine that's also possible we can also implement the get operation based on by D and a separate uh route for getting it by a reference so it's going to be a Warder worders slash ref slash reference let's also fine I'm gonna go back to our reference here let's start by simply saying response dot send and here getting order with reference and let's do request Dot params.reference okay that is our uh getting one order the next endpoint that we will need is for creating one order so create order endpoint we're going to use the router but in this situation we're not gonna use that dot get because creating an order is a post operator is a post operation and we are going to post directly on the on the root of our router here basically one of the slash orders and let's do request response like this and here yeah creating an order so the difference between a post and a get is um technically is the way it's handled but logically is the purpose a get operation is intended to request information from the server basically give me all the orders give me all the products and in a rest API a get operation should never update or change any data it should only read and get it back on the other hand whenever we have to update something um specifically when we want to create new items we are using a post operation post operation besides the basically URL and headers it will also include the body and the body is all the data that we want to save in the database so that's why whenever we are getting stuff we use the router.get for creating creating items we are using router.post whenever we are um yeah let me um go to them to the index because we need to um to add our orders route to our application so for that let's import it where the roads require router or the route and let's do up.use orders where they're out now if we go to our Local Host instead of Slash products let's try to do slash worders we will not see anything because there is no get uh endpoint for Slash worders and you might think why because we added in the route them slash here yes we have added it here but this is a post uh operation and whenever we are accessing the URL from a browser that basically is is sending a get operation so from this browser by accessing it as the URL we can not send post operations that should happen like when you submit a form or in a different way that I'm going to show you in a moment as we can see if I open the network tab and if I do refresh the worders Network where is it if I look at the orders we see that the headers here request method is get and we didn't implement the get operation but if I do orders then slash ABC which will act as a reference then we see getting water with reference ABC this is our first method here that has the slash reference uh I see a good question what does the dollar sign mean here um so the dollar sign here inside this special string because as you can see this is not a normal string a normal string is using double quotes or single quotes like this however if we're using the back ticks that are under them underway skate button this is called the template string and what it allows us to do is allows us to combine strings with JavaScript variables so we if with a normal string we will do hello my name is Plus name Plus and I am Plus age plus ears old if with a normal string we we can concatenate variables with strings like this with template string it's much easier by saying hello my name is and here to use the JavaScript variable we use the syntax dollar sign curly brackets and here we can use name and I am again a variable age years old so that's everything you need to know about the dollar sign and the template string with with the backtics it's much more readable than the one above do you agree it's less code and it's way easier to to build it especially when you have a lot of variables inside the string that was a little bit off topic but I hope you learned something new today if you didn't know about it okay okay okay where are we at yes we are finished with a weather uh route with a basic structure for our route let's move on to the database layer and let's open source database db.js because we need a new collection a new collection for our worders and we're gonna get it using database dot collection and here worders uh we will export it from our database and now inside our worders database file that we need to create now let's create in database worders Dot GS we can import the database using require and here we're going to have access to database.worders collection you may think that we will not have access to it because we haven't created in a similar way to how we created our products collection but mongodb will be smart enough to create it automatically if we if there is no collection with that name so don't worry about that it will automatically create one with this name that we specified here if there is no collection with that name okay so in the worders thank you very much no thank you what yes thank you water water from Alex thank you Alex stay hydrated guys all right all right all right so inside our database orders we're gonna have to implement two functions one of them is going to be called uh get water and this order will receive the reference and it will do something the second function that we need here is going to be create order create order that looks like a line from a dictator create word or and we're gonna receive a word or details here and we're gonna use the mongodb collection to save it there lastly let's go ahead and do module dot exports and we're going to explore these two functions get order and create order okay for the get Warder we are going to use them um mongodb operation but we already saw and here I'm talking about the find one operation so get worder will simply return a weight database dot orders we're gonna use find one and here we want to find based on not an ID but a reference and here we don't need to parse it to object ID because reference is a string so we simply search by a reference that we we have on all our orders and I can remove the second part because the key and the value is the same foreign was simple uh the second one the second one here uh for creating an order so let's go ahead and get the results by calling a weight database.worders and here we have a couple of methods to to add items in our collection one that we are interested in is the insert one there is insert menu as well uh so here if we pass one JavaScript object a simple JavaScript object it will go ahead and insert it there and because mongodb is a non-structured database it doesn't have a schema basically we can save any kind of JavaScript objects where even though we can be different so that's that's the Simplicity of it but at the same time we need to make sure that we keep some kind of rule there and a structure in order to easier query and work with our data foreign now what I want to return back here is I want to return all the data about the water but uh the thing is that um when we insert the Warner that uh mongodb will automatically generate the ID for this item and it will return it through the result so what we can do is we can assign by the here in order for us to know the idea of a newly generated item and we're going to take it from result dot inserted ID hahaha and yeah that's everything that we need from the database layer here okay let's go ahead and connect this and use these functions get word there and create order inside our water route so forward reference here um I think we're going to start with um we're gonna start with creating a water yeah with creating an order and for that we're gonna use the post request foreign yeah let me let me show you let me show you the problem and then show you the solution uh so if I do here console log request dot buddy let's go ahead and try to send a post request to our application and see what body do we receive to send a post request as I said we cannot do it from the browser because van is going to do only get requests we can do it with a form but that's gonna take a lot of time to build another way is using um HTTP clients like Postman or insomnia if you have one go ahead and use it but to simplify everything today I have prepared a command that is simply using coral to send a post request to our API and let's go ahead and copy this command from our guide and just to explain what is happening uh it's sending a post request here with specified post it's using the Json content type because we provide here a stringify Json of data to create the order and we're doing this on the route HTTP localhost 3000 slash worders if you're running on a different port make sure to update it here and if your endpoint name is different also make sure to update it here I'm gonna go ahead and copy it from here in that terminal I'm going to open a new terminal here and I'm going to paste the cool command it's a lot of things and if you want to see exactly I'm not sure if you need to see exactly but that data is this data in a normal format is also available in the dummy data here in New order.json so if you look here you're gonna see the structure of the New Order data we're going to talk about this in a moment now what I want to do is I want to send this cruel request so let's press enter and we get back creating an order because that's what we are sending here creating a order but let's move to the first terminal here to see our body well we see that there is nobody at the moment it's undefined even though we specify the body here the problem is that to parse her body we need another to parse the body from a string into a Json and to be able to access it easier what we need to do is we need uh to install and use another package and that package is called npm eye to install body Dash parser install it with NPI npm eye body parser and we need to add it to our application in the index.js here that's important not import command cost body parser equal require d by the parser and what we have to do is before our route here in a similar way we need to add them by the parser up dot use body parser.json and we need to call this now I'm gonna go ahead and probably restart our server just to make sure that everything is okay and let's go ahead and send this same request one more time this call request if I go back here we see that now our body contains the Json that we sent there with items with total delivery customer and so on this is in the information about one worder and this is the information that we want to save in the database perfect let's do that so in the water route Source router Wonder route we know that the request body this is that data that we need for uh for the order so let's go ahead and save it in the order data equal request dot body you'd go you in a normal scenario you'd go ahead and validate this data to make sure that the structure and the required fields that you need are there for the Simplicity of this project we're gonna skip the validation part and what we're gonna do is basically we're going to do cost new order equal we need to import the database methods from database worders for create order and then we're gonna also need the get order so in this new order we're going to call the create Wonder and we're gonna send the order data because we have a way to make sure that you are callback function is async for me it was automatically switched but yeah like you have to manually do it and yeah what we have to do is to send back this order to the client so the client knows why but everything worked okay so we're gonna send the status okay and for the data we're gonna send the New Order um leaving it like this is perfectly fine but usually whenever you create something on the server the server responds with a status code not 200 but 201 too um inform that something was created so we can set the status here to 201 to acknowledge that we created an item in the backend so with this being said here let's go ahead and try to send the same request again with curl we're waiting waiting waiting and then we should get back there the item let's see why taking so long rename to order data thank you not a huge problem but I'm gonna do that in a moment not sure why it takes so long empty reply force from server interesting I'm gonna rename the data but that's not the problem uh wait create order let me check if everything goes okay here let's go ahead and check if our if in the database something new appeared if I look at the collection I don't see anything new let's try to do it again I'm going to restore the server and I'm gonna send this request again and we get back the status okay with the data and the items but look closely that the last property of this item is where the last property of this object that represents one new order is the ID and this is the idea of a newly created order and now if we go to the mongodb atlas and refresh the page in the collection we should see a new collection of orders that has one item with this ID that we solve here so if I search here is the ID this item has this order has an array of items that specifies what products what size and what quantity of that products was added that basically everything from the shopping cart then it has information about the total subtotal and so on and lastly information about the customer like name email and address because we are not going to use authentication all the words will contain information about the customer-like address and so on to know how to fulfill that order all right one last thing is with that reference what I was talking about what I'm what I Envision this application to work better because you do not have an account in this application and you simply open replication order something and when you come back to the application we will not be able to know what are your past orders that's totally fine I think a lot of applications are working this way without having user accounts uh without making users to go through all of the hustle to create an account set everything up if it's it's a simple application like hey come here word around that's it in that situation we need a way to allow users to track their orders one way to do that was to basically give them the order ID and say like Hey whenever you need some information about word already give it to us but as you can see this order ID is not very um human friendly like it's a very long string so that's one problem the second problem is that usually you don't want to expose IDs of your items uh to the public they are mostly to um to be managed internally so what I'm thinking is for every worder to generate a random string like a short string that you can remember where you can take notes and based on that reference you will be able to track the details and the information about the order so what we have to do is in our order route I want inverter data to add a new property reference that is going to be something like one two three to generate a random string I'm going to use the next syntax here that you can copy from here in the guide which simply generates a random string um of five characters if I'm not mistaken so with this yeah like we're attaching a new property to our order that is a random string and based on that we're going to be able to search it later let's go ahead and send this request again and in the result we should see already the ref which is 3D to py and as well you can see that if you look in the mongodb atlas here foreign there is a ref with this item and the cool thing is that now we can search based on this reference like this in our mongodbit database and if I apply these filters I get the worder with that reference so that's a much more human friendly way of looking based on some kind of IDs instead of giving that long idea we generated a shorter one and now what we have to do is to implement in this router the function to get the word there wait get Warder and we're gonna get it based on the request Dot params dot reference we need to make this I think and yeah let's do some error checking here as well so basically if we didn't find the worder what we want to do is we want to to send the status code of 404 and the data here will be status failed and error whatever not found and after that we need to stop execution here and otherwise if a word that was found we can send it and then here tattoos okay and data will be wider okay so let's go ahead and test that so we have this order ID here if I'm gonna access the localhost Port 3000 slash warders slash this um this reference yes right away we see the information about that order and if I'm gonna give some random strings here we're gonna see where they're not found perfect that's exactly what we wanted and guys we this being said we are done with our back end we are done with the API methods that we are going to need to implement in The Next Step that we're gonna do in this video and the next app is going to be to integrate this API inside our react native application and to query it using Redux toolkit query that's going to be fun who how is it going guys uh Amar check out the Tesla clone build that we have on this channel that is a very beginner friendly build that a lot of people even with no experience managed to follow along and to learn and to get started with mobile development with react native so go ahead and start from there how to deploy a mongodb project for free because Heroku has become paid Oliver when it comes to mongodb you can use the mongodb atlas and that's what we used in this tutorial to run a database cluster for free it's not very performant because it's for free of course and it's intended mostly for um for development but still like for some test or staging databases it's perfectly fine but if you're asking about the API um then I don't really know any solution for hosting the API for free where might be where it definitely should be but it really don't um yeah basically hosting stuff costs money servers cost money and we should be used to that um for for projects that I've been using um I've been using AWS running a ec2 instance and hosting my API there and yeah like I was paying something a month but that's expected but that servers cost money the video name for beginners uh the title of the video is your first react native application and in that video we are building a Tesla clone in is very beginner friendly what is my device I'm working on a Mac Studio device Kimball is saying taking water boosts productivity taking water yeah when developers are hydrated they are less likely to experience fatigue or brain fog which can improve productivity and ability to concentrate hashtag no just depth let's go was that generated by chargeable team tell me guillermere uh will we see more about free jazz on Rec native really enjoyed that content I've been working with react native for some years and never thought about using free just with it uh we might we might because I really enjoyed it as well however it's a very Niche and very specific use case and it really contradicts a bit with my beliefs of of learning and doing the minimum necessary in order to get something out there so I feel that if I'm gonna teach like a lot of free GS people will believe that without having some crazy 3D animations in your application your application does not deserve to be published out there and yeah that's what I want to prevent I want to encourage people to build more application and to launch more application out there but it's definitely like a very cool tag like um I I saw them the starlink mobile application is using 3GS and that's that would be so interesting to to clone it to to build it as well I loved your blog on Redux um if you're talking about getting started with freedax that's actually not written by me that our new technical copywriter is sad uh which join our team and is helping us with a lot of content and it's also helping me on the academy side because we have so many students there and we are trying to help everyone so yeah Sadi is doing a great job on covering a lot of topics as well so basically here's the reason why we are doing the Redux series now so I'm super happy about that foreign don't worry you can follow this video in the weekend because all our videos stay on the channel in our public said I knew you would notice yeah chai gbt the power of charge gbt it was too perfect it was too yeah all right can you explain more about the AES build uh that's probably a topic for a completely different build for a completely different uh video or tutorial add 3gs to the shoe which is added to the card actually uh in my previous video we have implemented this 3GS specifically for this application well the thing is that we didn't include it here just because that's an optional step so I showed you how to build that cool 3D animation for the shoes with 3D stuff so you can check it it's on the channel it's our previous video mm-hmm just started no no actually we are at the middle of a video uh we finish the first part so for everyone that is joining right now I'm gonna quickly do a recap of what we are doing now so in this uh tutorial we are building the Nike application backend using node.js and mongodb and we are going to query this rest API from react native using Redux toolkit query so this is based on an e-commerce application on the Nike application so it will be a good tutorial for anyone with our building e-commerce application on the side and yeah we have now finished the first part that including building the rest API using node.js Express and mongodb we have four main endpoints that we need get all products get product by the create worder and get worded by a reference and with this four endpoints we are ready to move to the second part of the tutorial where we will query the API from the react native using react native or Redux toolkit query so guys if you enjoy this tutorial make sure to smash like subscribe to my channel uh because that will help us a lot in reaching more developers and helping even more people become full Stack mobile developers I appreciate that thank you thank you why not use amplify because I wanted to focus on something new and something different a lot of people asked about building node.js servers teaching Redux so here we have it that's why but we're not leaving amplify amplify is still a great tool and I can't wait to get back to it because I realized that probably for two months I haven't done any tutorials with amplify foreign I see you're very active today guys in the chat keep them coming leave your questions there and once we're done we can go back and look through some questions but you left uh but now um yeah now we are going into the second step of our project um and as I said in this part we are going to query our rest API from react native using Redux toolkit query please do not spam thank you very much um I saw the message I saw thank you very much I appreciate it okay so moving on um replication that we're going to use to integrate this in we have done it in the in some of our previous streams in the you can find the url here and this is the replication the user interface if you haven't followed that which I highly recommend to do because that will teach you how to build the Nike application user interface and it's a lot of fun building it however if you haven't done that or if you need the source code you can find it here I attached a link to in the guide and if you switch to the UI branch this is going to be the branch with a code that we're going to use to start from today because later on in the main branch we're going to have the updated code so make sure to switch to the UI Branch to use them latest code okay what I'm gonna do is I'm going to open a new vs code window where is it come on new window and I'm going to open the Nike application clone this is where project the UI branch actually I'm going yeah so after you push your pull the repository go ahead and check out to the UI branch and if you do get status you should see on Branch UI in order to for everyone to start from the same place okay here uh let me this is optional only for me I'm going to switch to a new Branch backend in order to leave that UI for yourself for you and in the back end go ahead and install all the dependencies of the application for me that should be already installed but for you go ahead and do npm I to install body penises and once that is done we can start the development server to run replication let's go ahead and run it on iOS and where is it come on here we have it let's wait until the application has finished building and running on our simulator is the documentation available for you yes then step-by-step guide you can Access Link in the description below thank you w okay so here we have our application from the first episode I'm gonna quickly review what we have here so the main page is a list of products sorry uh whenever we click on one of these products uh it displays the product details and what we can do is we can press add to cart that will automatically add things to cart and we can access the card by pressing on this icon in the header and we see that we added one item to a card we can go back select one more add to cart that will add it again we can add more items we can delete items so yeah that's what we have managed to build in the first episode of this series and um um yeah everything is done in rack native and using Redux as a global State Management actually I highly recommend you checking that tutorial uh especially if you don't have a lot of experience with Redux because in that tutorial we are teaching a lot of Redux so you need that knowledge in order to follow along with today's tutorial to query our API because we are going to also use the Redux toolkit to do that um so uh what we're gonna do now yeah as I said we're gonna use the Redux toolkit query which is a package that is provided by the Redux toolkit and it allows us to interact and fetch data from apis I think it's bad for a long time fetching data with Redux was a pain invest just because Redux um Redux does not offer a lot of features it's like Bare Bones and developers are free to implement things on their own and when you do that everyone was doing things differently uh the problem was that you had to write a lot of code yourself for example especially for fetching data because there is a lot of common logic when you fetch data like handling the loading state updating the UI when there is an error when there is a low there is loading caching all the data so all of these things was done manually until Redux toolkit introduced them reduxed toolkit query with this it becomes much more easier and a lot of things are handled by Redux toolkit uh like caching like managing the loading States and so on and for us what we have to do is to Define how we want to interact with our API and then use some hooks that are also Auto generated by Redux toolkit to query this data in our component so the first step that we have to do is a similar way as we have defined slices for our card or for our products we're going to create a new slice specifically for our API so let's go ahead and create a new file API slice.gs and here we're going to Define our API slice for that we need to import the create API function this is going this function is going to allow V is going to help us create them um well yeah like basically the interaction with the API the Redux toolkit query and we're going to import it from Redux toolkit then slash uh query and we specifically want to import it from queries slash react because you can import it from query it will work but it will not generate hooks the thing is that we need hooks so that's why we import it from react okay let's go ahead and create our API slice and Export it from this file using the create API here it needs some parameters and these parameters will gonna Define right now first of all is where reducer puff and this is similar to other slices that we have defined for example for a card it has a name here we need to specify the reducer puff and the reducer puff we're gonna name it API and the next one is the base query where we specify the base URL that to which we're gonna add like other parameters for the base URL we're gonna use the a function called Fetch based query from from the same import so let's do fairbase query and we need to specify the the actual base URL where do we get the data from let's go ahead and find this URL in a variable base URL and our base URL is going to be at the moment the localhost similar way as we have been querying it from where is it from the browser localhost at Port 3000 that's going to be here HTTP localhost and your port if you deploy this your API then your base URL will be different and the last thing that we need to specify here is are the endpoints and the endpoints are uh here we're going to specify how we want to query all our endpoints like getting worded creating the word Earth getting a list of products and so on the endpoints we're going to create using web Builder and yeah here we're gonna return an arrow an array of endpoints for now we do not specify any endpoints we're gonna come back a bit later to add them let's finish like connecting everything together you know in order to connect our API slice with the main Redux store what we have to do is to go to the store index.js and connect it to the reducer here for that let's import API slice from the API slice file and let's do API which is going to be API slice dot reducer foreign besides the reducer whenever we have um uh react query toolkit we also need to specify one middleware so the middleware uh let's get it from the guide here I'm gonna scroll down in the store index here so here we get the middleware and this middle area is going to be responsible for uh caching polling and validating so basically to making artiki query rectal kit query work okay okay now um our API slice is connected to the main store but there is one more thing like we need to go back to our API slice and Define some endpoints that we're gonna use in our application so let's start with the two endpoints for our products the first one is get products so we're going to define a function with the name that we want in this case I want to call it get products and using the builder.query let's define how we want to um to execute this get products query to get data from the API what we have to do is we have to specify how we want to build the query itself so basically what we want to do is we want to query the slash products products so what this will do is it will attach the slash products to our base URL here and we'll return our products okay forget products it's simpler but for get product which will be a function to query one specific product we're gonna also do a query but in this situation we need a parameter so the function right now is going to receive the ID and the URL will become product slash and hereby d so product slash ID here I'm going to use a template string but I was explaining before to add a variable ID here so now when we will call get product and send one ID there what we are actually going to do is we're gonna execute a query on the localhost 3000 slash product slash ID okay now our create API because we imported it from react will generate hooks for these two endpoints and the hooks are going to allow us to easier execute the queries in our application so let's go ahead and Export these hooks export const and we're going to export them from API slice and we will be called use and then the name so for example use get product query this is get product and the next one is use get products query so one is product one is products okay so what we have done here is we exported this to uh hooks from our slice and that will allow us as I said to query this data easier in our uh component in our screens to do that let's go ahead and view screens and we're going to start with a main home page screen that is our product screen here at the moment we're taking it from the product state that is dummy data what we have to do is yeah like we're not gonna need it here because we are going to use um and let me let me leave it for a moment and we're gonna change it a bit later so as I said we need to import use product query from store API slice and using this query we whenever we use it inside our component it will execute the query to our API and will return us some information back this information will be data it will be is loading and it will be error these are the most important things that we need to know so um if you're familiar with Apollo or other querying library or even react query you should be familiar with this um with this way of running queries so basically everything like loading State error handling data were managed automatically for us we don't need to handle this ourselves and now in our component we can simply say if is loading we can show a loading indicator so we're gonna return an activity indicator if it's Error we can return basically a text saying error fetching products otherwise let's go ahead and start by console logging the data console log data so if nothing happened there and we already see the data here in um yes return and here we see data with all the items that we have here okay so that means that now we don't need the products from the dummy data State there because we can take the products from the query data so coins products equal data the thing is we're going to use data.data because that's the first data is this name and the second data is the way that we called it in our API and right over that we have our items queried here you might think that nothing changed but actually these are items that are coming from the database if we're gonna click on one of them it's gonna say error because the next page is not yet implemented with querying these items so that's why it's a problem but yeah like this information this data is coming from the database we receive a loading indicator that's another addition to our application because when used get products at this moment is saying that the data is still loading so if I refresh we see loading indicator and shortly we should see the actual data Arrow fetching products let's go ahead and also specify the the error Dot message will it say something no error doesn't want um data Dot error let me console log error here to see it in them error type error network request fail status fetcher okay so I can do here error dot error yes Arrow fetching products type error network request failed and I suspect that something happened with our reserver so let's go ahead in our server and make sure that it is still running if I look I see the node mode crashed waiting for file to change why it crashed I don't know because maybe someone is trying to access it connection timeout I don't know what happened there but I'm gonna restart the server and I'm gonna refresh my recognative application it's loading and don't tell me if it's someone is messing with me right now are you guys tell me I need to know um hmm let's see let's investigate something wrong with my internet I hope no all right okay let me see what's going on come on thank you okay I don't know I restarted the server and everything is working so I'm okay uh okay so we have here our data that is coming from our API that is coming from our database and if we're going to change or add some products to the database when you refresh the application that's gonna be reflected in our mobile application so here we saw how we can query our database using the generated hook um for the like getting products using this hook we get back three important things data that contains the response from the server when it is available initially data is going to be undefined uh it contains loading that is true when when we are waiting for a response from a server and false when we received either response were an error so this is easy way to handle um loading states by displaying some Spinners in your application or handling how your application should look when we are waiting for a response and we also get the error back that we can handle and see what we should do in the user interface as well so from yeah like from our from a react native part like it's pretty simple from the API slides here it might be a bit more confusing and for me as well it's confusing a lot of things are steel boilerplate for me even for wrecked toolkit is saying that they their goal is to remove a boilerplate that you have to write when using um Redux so still there are a lot of things that you have to do and you have to remember like the Builder query another query the function yeah like I understand like if it's confusing don't worry like it's okay uh we we can have like these examples and just to understand how everything works from a high level perspective we can easier replicate this for other scenarios as well um uh so we have integrated the use get products query in our main page here the next step is for the second page uh we have to implement the use get product query so this page is going to be inside our screens product details screen but before that whenever we press on one of these items inside the product screen we have this principle so whenever we press on one of the sneakers here what we are doing at the moment is we are dispatching an action to change the selected product well we're gonna switch the logic here because instead of setting it in state as the selected product I'm gonna comment it out I'd rather send the idea of that product to the product Details page like this item dot underscore ID use vendorscore here because the in the database our IDs are with underscore and now going to our product details screen product detail screen ah we're going to get that ID from the route so we can get const ID equal route Dot params dot ID and I can console log here and we can check by pressing on one of these items nothing happens but if I scroll up a bit until I see some IDs where is it the problem is yeah like the product is null here so I can add another check here if product is null uh return null just not to give me these problems and now here in the terminal if I'm gonna press on this I see that uh what params not route I want to to console log ID so now if I'm going to go here yeah this is my ID go here this is the ID perfect now knowing this ID we can use them uh the query to get the information from our API about this product so we're gonna use the use get product query not products but product make sure very important now a similar way we're going to get data loading and error using the use get product query but now for this hook we need to send some data in the API slice for the query we have an ID here so that basically means that we need to send by ID from our hook in the product details screen by D is our ID that we get from the route now having this loading error and product we can go ahead and do here if loading but not loading but is loading is loading we want to return the activity indicator to show a spinner if it's an error let's go ahead and return a text with error fetching the product and we can also specify error.error otherwise the instead of this if statement I'm gonna say our product is going to be equal to data.data and we should also double make sure to delete the old way of getting that product so let's delete it from here now if I'm gonna go and open this one we see that the data is coming from our API and you see initially it's a very short loading indicator and after that it displays the data um but yeah that's that's how it works another cool thing about react uh toolkit query is that it handled caching um automatically and what do I mean by that to explain what I mean by that in a side our back end in the router for the products when we are querying all the product no when we are querying the product ID let me do a console log query product with ID and here I'm gonna do request params.product ID let's open the terminal here and let's press on one of these items or let's refresh the page first I'm gonna open the first item and we see query product with this ID okay I'm gonna press on the second one query product with this ID perfect that's what is expected and if I'm gonna go back to the first one I don't see a further request because react toolkit query will automatically cache that result and if we're sending the same request twice it will not send it to your backend and that will highly improve the performance of your application again if you look at some data that is not already in the cache it will reach your server but if you go to a to a product page that was already loaded it will not send the request twice and that's that's cool that's what you would expect from um querying library to to have cashing out of a box Okay so so we saw how and we saw and we implemented the uh queries for our products getting the products from the API here and getting one specific product on this page and so to see that it's actually coming from the database you can go ahead and look at the uh collections uh four products you can look at probably the second one where let's try to find it by name Nike reacts yes I found it and I'm gonna update it to Nike react and I'm gonna update it and now if I'm gonna refresh my application and open this page again we see that the name has updated correctly and that means that yeah like our data is actually coming from a database and it's not coming from our dummy data foreign okay so I hope you are managing to follow along and to understand what we are doing so far we have finished with integrating the products uh API endpoints in our mobile application the next step is going to be to implement our worders API endpoint and for that we're gonna look how we can send a post request to our API using Redux toolkit query to create a new order whenever we press the checkout button and also then we will implement the querying with data about the worder to to display it based on the reference so if you're ready yeah if you're ready I am ready and we can go ahead and start and continue with our API slice so I'm going to close ours um let me go ahead and add a commit here and do products API integration and now we're gonna continue with our worders for that um let's go ahead and open the source store API slice to add new endpoint for our API and when you end point here let's do them worders the new API uh for for the water the first one is going to be the create order it's funny create order uh we're gonna use the Builder dot not query because query is when we want to send a get request we want to do here a mutation and the mutation is for our post whenever we want to send a post request or a patch to update some data so uh in this uh yeah we need to Define here how we want to build the query that is going to reach our database and here instead of Simply specifying the URL we will specify an object because whenever we send a mutation there is a little bit more information that needs to be sent one of them is yes is the URL and the URL will start will be orders uh but we also need to specify what method what HTTP method to use and we're going to use a post HTTP method and lastly we need to send the the body basically with data but we want to send to the server the body we're going to receive as a parameter from our from our shopping cart component so we're gonna simply receive it as a parameter and send it as a body there while we're still here we can implement the get uh word or by reference method so let's add one more here get order and this one we're gonna use a builder dot query because it's a simple query and for the query we're gonna get the reference and we are going to send the request to orders slash and this reference like this okay so we have this create order and get worder endpoints that means that the create API function automatically generated um hooks for running this mutation and query so let's go ahead and use these hooks so one of them will be use create weather mutation and the second one will be use get word or query we're going to start with a mutation for that we're going to go in our screens where should this happen Network request failed something wrong with my server again I think I'm connecting too many times to where to the server to the mongodb and that can be because in our database here we are connecting multiple times there we can optimize these to to prevent multiple Connection by by saving the connection in a variable and then checking events um but yeah let's for now try to restart it and see if we can prevent that okay that's not very Bueno uh we're connecting too many times to the same server [Music] or someone else is also connecting to the same server which I think is the case to be honest breath is saying I have learned a lot from you I appreciate that I'm happy when I hear this there are 15 connections currently foreign incoming connection to a database uh so Mom going to be too many connections we're gonna investigate together let's go yeah the problem is uh as I was expecting the problem is that every for every query that we do we basically create a new mongodb client and that's not the preferred way of doing this so let's try to optimize this and to save our client into a variable and use it if we've already connected to it so um we're gonna have a function connect DB or yeah get DB and that function what is going to do is it going to basically do all of this stuff initialize the client connect to the database get a products worders and lastly it will return products and orders these two collections now instead of exporting this here because we don't have access to them we're going to export get DB function so this will not solve a problem because we still create this connection over and over again to solve a problem let's go ahead and Define the client on top here let client and we're gonna check if uh uh yeah here we need to remove a const client to use the same client from here and we need to say if client is null only then create a new client otherwise use the same that was already generated and then do the same thing the next step is from our worders um instead of DB here we're going to import get DB and we're gonna call this get DB here dot orders and so on the same here and in the products as well get DB get DB and get DB so now uh the connection is supposed to be reused whenever we are sending multiple requests so let's go ahead and try again it might still fail for a bit until it closes the old connections because they are somehow still open but once it frees up the previous connections it should be um we should not get into this error again let me see if I can somehow close it from from here cluster if I look at real time into so for connections connections here it is still at 15. foreign connections come on I need just to get one connection and after that I think it's gonna work I could probably delete it and create a new one if I go terminate foreign let me let me try to go ahead and uh create a new database we've shared create give me just one second I think that's gonna be much easier create cluster so it's only one cluster per project okay new project Nike up two create let's create a database shared create traffic lights moving DM and for a password I'm going to Auto generate one and copy it no it's okay okay okay okay and add my IP whitelist finish and close go to database uh now I'm gonna choose connect and I want to connect from the application let's copy the connection code from database DB here from the back end I'm gonna update the url url and I'm also gonna paste the password I think I'm not going to show you this type of password even though I don't think you can access it as it is only my IP is white listed but um and let's go ahead and try to launch it again so here in the code API is listening if I refresh products this time you should work products if I refresh status okay yes but there is no data perfect because the last step is to go ahead and populate the data in the collections so I'm gonna go ahead and add my own data in the test database with a collection name products let's go ahead and create it and I'm going to insert them come on from product.json let's let me copy all of them and from here let's insert a document and let's insert all of them insert nice and now let's refresh the rec native application and we are back to where we started but now our database connection is going to be reused uh so if we do more queries that's not going to open new database connections I hope let me actually check that um in the real time I think metrics thank you current two yeah I think one of them is the Atlas and one of them is this one protein again I think I didn't I think I didn't improve it okay let's let's move on until we crash it again and then I'm gonna see what's the problem there no I cannot do that if I go to the database.js console log creating a new client and else console log re using the old client oh maybe oh maybe because my application is launching over and over again with node mode and yeah node monies launching application over and over again and that causes my database to connect over and over over and over I think so so what we have to do is uh in the in the package.json here instead of a Dev script let's add another one start that will simply execute node source index.js and this will not restart the server so many times so let's do npm Run start it's still listening creating a new client but the second time it's going to reuse the old client and now everything should be okay so back to um back to our react native application back to our react native application so what we have implemented so far just to recap we are querying them products from the database we're querying the product details also from the database now we can add things to the card and when we go to the card there by pressing here why you're not adding to the card come on add to card add to cart adding to the card why it's Chris shopping cart button check out no product details screen we have onto card item product yes the problem is with this product at this moment is not available we need to declare it a bit more on top here now if I do add to card you should be working and I need to access it safely add to cart second one uh to current it's not adding nice ah two card item actions if I go to the store card slice Where is the autocart yes yes yes because at the moment our card is working with IDs but our data is working with underscore IDs so we need to make sure to update this to underscore ID underscore ID and that's it now if I add one item to the card and add the second one it's gonna work properly okay that was uh expected okay so oh no and now again let's make sure that everywhere we are working with ID we are actually working with underscore ID term product yes and now if I'm gonna add more of them if I change this one no cart item.quantity change quantity let's see where we look for we call the change quantity in the cart list item and here again we are working with ID so we need to make sure it's underscore ID and for the decreased quantity it's also underscore ID and now it's working it's working yes so some some changes we might want to check other places where we're working with DOT ID and that's uh yeah product slice the product slice yeah we don't need it anymore okay so now that we made our cart work again as it works as it was working before what we want to do is whenever we press on this checkout button we want to execute the create order mutation so in them shopping cart let's go ahead and import uh use create order notation from the store API slice inside the function shopping cart it itself let's go ahead and um use the use create order mutation and this hook instead of giving us back data error and is loading it's going to give us back instead of this thing it will give us a tuple with two values one of them is the function that we will call to execute the mutation so we're gonna call it create order and the second one is the result so basically the second one is what we expect here data error and is loading so we can already say yeah we can console log sorry um is loading maybe data on this page we have a checkout button so whenever we press on this checkout button we want to execute a function so let's define this function on create order and for the button on press we will on press we will call this on create order create word come on create order so it won't create order we need to call this API function create order uh uh we're going to send their um some data so it's going to be an object if you remember from our [Music] um dummy data the New Order structure should look something like this it should have an array of items it should have subtotal delivery total and customer information so for the items where is it oh my God this should be here so for the items we're going to get them from card items basically all the items from the cart we want to add them to the order then for them subtotal delivery and total let's go ahead and take them from where well if we scroll down if you scroll up a bit in the involver component we see how we are taking the subtotal delivery fan total also from the Redux tour so let's copy this from here and use them inside our shopping cart as well because we need them for the subtotal here for the delivery fee here and for the total and lastly for customer information we don't have data at the moment but we can uh put some dummy data here hard code for example the name is Vadim address my home and maybe email if we want to ask the user for email so that he can send we can send him some emails with order information okay just by doing that let's go ahead and try to press on the create on the checkout I will press on it nothing happens we can look in the console of our application and we see and define false and define false and lastly and Define true that I defined through is for the loading and after that the loading finishes which means that now if I'm gonna check our collections I expect to see one order in our database in your case and yeah like if I press one more time and refresh it I should see another word there is it two in total yes where two it has a subtotal which is exactly what I see in replication if I change it a bit for example like this and do a checkout that should be reflected in the information that we save in the database for the last one total 507 and the reference is V1 M yeah I'm gonna say it oh so what that means that means that we have correctly created the order uh the last step is to show some user feedback on the screen for example whenever uh uh whenever we are submitting the order and we have this is loading maybe we want to change to the checkout of the name of a button checkout um to were to add an activity indicator here after checkout so what we can do here is put it from a new line and conditionally say if it's loading let's add an activity indicator from react native like this and if I press checkout now I see the activity indicator very fast and because our API call is so fast it right away disappears that's one way to show like that something is happening like it's loading uh another thing is that I want to tell the user that hey everything worked correctly and here is your reference number so for that I'm going to get the result out of this create order using a weight and let's check if uh result dot data dot status is equal to okay and this can also be null so I'm gonna do it like this so if everything worked correctly what I want to do is I want to use a simple alert to say word there has been submitted and your Warder reference ID or yeah your order is and here we're gonna put results dot data Dot and number time data because that's how we send it from the back end and then ref yes yes and now if I'm gonna press on the checkout possible handle rejection what why is that turn something to the card check out can find variable results because it's a result so check out where there has been submitted successfully your word of reference is in this number awesome so we tell the user that everything was worked correctly we show him that um his reference ID reference number with which he will be able to track it in the next step we're gonna do that uh the last step is that I really want to delete all the items from the shopping cart because after you order them that's what usually happens in an e-commerce application so for that inside the card slice of our store I will add other reducer I will add the reducer at the end here that will say clear shopping cart this reducer will simply get the current state and we'll update them items to an empty array so it will reset it to the initial State and just by removing the items it should be items not item it automatically will recalculate the subtotal Deliverance so on but we still have to call it and we're going to do that from the shopping cart.js from a screen shopping cart after we confirm that the order has been created so here we're going to dispatch first of all we need access to the dispatch equally use this patch and we are going to also need access to their card slice and here clear or no card slice itself so now uh in the oncreate order after we got the result we are sure that the weather has been created and everything goes okay now we can safely dispatch the card slice card slice dot actions dot clear and that will go ahead and clear all the items from a shopping cart let's go ahead and test it out I'm gonna add some items there I'm gonna go to the cart and if I press checkout I see that water has been submitted with this ID and our shopping cart has been cleared out so yeah that's uh how it's supposed to happen I guess all right so we are creating our warders successfully the last step is to given the possibility to track these orders so what do we have to do for that let's go ahead and create a new screen for the tracking rewarder so in the screens actually I'm gonna go ahead and commit everything create where their API integration and yeah let's go ahead and create a screen for tracking book order so track order.js I'm going to initialize an empty component with their react native react Snippets extension and vclx is a simple blank component now we need to put it in our navigation so let's open source navigation and in our navigation here we're gonna put it somewhere uh basically let's do it after the card so stack dot screen the name is going to be uh track order and the component is going to be track order screen that should be imported make sure to import it from the screens what's going on there yeah I also need to close this component okay now we have that screen but there is no way to navigate there so where will we do that from uh we're gonna do that from also from the products page I want to add them and I can hear in the header left so for that the same way as we are doing with header right let's check where it ends it's here we need to specify header left so this is going to be a function that will render what should be displayed in the left side of a header for that I'm going to go ahead and get this from the guide it's um yeah this one header left material Community icons simple icon that when we press on it will run will redirect to the track order and we need to also make sure to import material Community icons from Vector icons here now if I press on this truck in the top I go to a page called track worder nice so having this um having this page here uh if you remember in our API slice we have implemented the getting worded by reference um query Okay so so we need to call this get word or by reference using the hook use get word or query so let's go ahead in the screens track order and here we're going to use this query we're going to get the data is loading and we're also going to get them error use get order query these use get worder query should receive a reference so a reference like the one that we can get from a database or the one that the user will receive now this data but where do we get this reference for that we need a text input on the screen so let's go ahead and import the text input from Rec native text input and render it here I'm going to go ahead and import this text input from our guide uh uh here we have our text input and also I'm going to import the styles that I have defined here not to waste time on them tile style sheet should be imported from react native and we need to define a state variable for the value of our text input and that value is going to be called ref and set ref we're going to store it in a state using the use State hook on change text set ref yeah like that so if I go here now I see your weather preference and for this view I also have to give styles dot root okay so now uh if this ref should be used as via input for our query and in this way uh in this way whenever we change the reference here we're gonna execute the query and we're gonna display down below what is the result so let's go ahead and display the result here below the text input first of all I want to render if it's loading I want to render a loading indicator activity indicator uh so if I write something I see the activity indicator now I also want to handle the situation where the water is not found so if data dot status is not okay I want to Simply render a text saying word or not found so if I write something like this word are not found perfect otherwise what we will want to do basically if data dot status equal to okay here we are going to render details about the worder for now I'm gonna go ahead and simply render web data dot data Dot and put make it as a string so Json Dot stringify and add some maybe null and to here and let's grab an actual reference from our database like this and paste it here and right away we get information about that order if I change something it will still render the same order because uh it's going to be cached but if I change the reference to a different order for example this one with c y s one free I think should be lowercase in my situation it automatically updates and we see a different order ID okay so um that's how we query uh where they're based on their reference the problem with this solution is that we will rerun this query we will send basically this query every time for every character that we change here so that's not very performant and sometimes you want to add some debounce meaning that we will send the query only when we stop typing for a couple of milliseconds for 300 milliseconds for example or in other ways to add a search button on the right or somewhere in the UI to execute the query only when we press that button and in that situation instead of using a normal query you will use a lazy query that is going to that you're going to be able to call only when user does an event basically pressing a button uh I'm not going to implement the UI for this page because because I didn't have time to prepare it but that's not the point of this tutorial what I want you to do is how you can build a rest API with node.js Express mongodb and how you can query that API from react native using the Redux toolkit query and I think that you learned a lot today in this video that's everything that I have prepared for you uh if you enjoyed it make sure to subscribe to the channel turn on the notification Bell because we are going live every single Friday with a new tutorial with a new project based build and yeah we're learning a lot on this channel let's go ahead and see a couple of comments um before we start the weekend actually I'm here in Tenerife I live in Tenerife and we have the grand parade here so it looks something like this let me try to Tenerife him uh Carnaval Carnival how do you call it Carnival so today is almost the last day where everything is going crazy here so I cannot wait to uh to go there with everyone so yeah we're gonna get dressed previous year I think more than one million people were here so it's it's it's a crazy thing all of these people get dressed everyone is having fun I don't know where uh Spaniards get so much energy for for parting because I was going this week to the gym at six in the morning and every time I was going to the gym I was seeing people dressed up and coming from a party like throughout the week like come on guys how where do you get energy from but yeah probably everyone with their own priorities Uber Eats clone uh Hey hero we have done that it's on the channel you can check it out if you simply search Uber Eats not just Dev you're gonna see it's a huge project with uh five days actually seven serious projects so it's a very very in-depth project which I hope you will enjoy what about adding payment that's a very good question I was thinking about as well I will not promise but I really want to to see that coming next week so hopefully we will do that come on guys don't spam that's not nice I see it I see your messages it just takes a bit of time for me to process them I'm not that smart and after three hours and a half of coding like it takes some time so just copy pasting your message will not help at all so guys so I hope you enjoyed this uh have a great weekend ahead I'm gonna go have fun at the carnival here in Tenerife and I'm gonna wait till next week with another great Bill maybe we're gonna do the payments so stay tuned subscribe turn on the notification Bell leave a like if you enjoyed and bye bye guys
Info
Channel: notJustā€¤dev
Views: 23,708
Rating: undefined out of 5
Keywords: vadim savin, not just development, notjust.dev, react-native tutorial, react native ui design, react native live coding, live coding, javascript, react tutorial, react native tutorial, javascript tutorial, react native ui, Nike, Sneakers, nike shoes, Nike app, react native for beginners, UI/UX, CodingTutorial, redux, node.js, mongoDB, redux toolkit query, build a database, database, backend, API, build an API, query apis
Id: FS8DbIaSsBA
Channel Id: undefined
Length: 198min 3sec (11883 seconds)
Published: Fri Feb 24 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.