NEXTJS + FAUNA CRASH COURSE - Learn the basics in under 1 hour.

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys and welcome to the video in this video we're going to be talking about fauna db and how you can integrate that with your next js applications now fauna db is actually built for the jam stack so it's going to be the perfect kind of database for your next js applications so by the end of this video you're going to be able to read data from your fauna db as well as insert a new row into a collection now if this sounds interesting to you stick around as we travel through the world of fauna and how you can use it in next.js so before we get started into how to use for db and how nexjs seamlessly integrates with it we should talk about what fauna db is and why it's different than say your standard client to server relationship so it's basically a giant serverless function that you can call to update your collections insert read delete all those things that you can do with a regular database except from it's built with serverless functions in mind so a good example of this is the client-to-server relationship now back in the olden days before even i was a developer we had something called the monolithic and client-server relationships now in the 70s what happened was the application did all the business logic and the database kind of stayed behind and then the terminal was presented with whatever data you needed then in the late 80s and 90s we started using databases for business logic and then doing the presentation to the computer which is slightly different than before where everything was handled in the application then the three-tier system came in and this was like the 2000s and until relatively recently so you would have the database at the bottom the app server would do all the business logic for you and then the web server would do the presentation so just think about like a node server and then something displaying it on the front and obviously then you have the rest version of that where it's all wrapped in the rest server and it's displayed to your users now the way that this works now is client serverless is is pretty special so the browser and the mobile does the presentation logic the cdn also does some of that so it will you know serve up cached versions or it will serve depending on what country you're in all those kinds of things then the database and the compute which is you know for sale will do all of the business logic for you and then finally you have services that you can use like twilio or stripe etc etc so you can imagine it as just a bunch of little micro services maybe and each one of those does its own thing and you can just tap into them depending on where you are in the browser versus the other way when you're looking at this three tier where you have to have the app server involved at all times now we've talked about that let's go ahead and create a fauna db account and create our first database and once we've created the database let's go and move that to the next.js app and start showing how you can use server's functions to get the data and display it to the users so once you've created your account what you'll get is a screen that shows create your first database and that's exactly what we're going to do so click the create new database and then give it a name and the database cannot contain any spaces so let's call this next with fauna and we're going to use the pre-populated data so go ahead and click save and in a few seconds you'll get this screen now in this screen you have two pieces in this dashboard uh that's important for us and that's the indexes and the collections now the collections you can think of as tables and the indexes are obviously just like indexes in any other database so inside of here you will see that there's a few customers and inside of the customers there's a bunch of different data here first name last names addresses telephone and even your credit card numbers and that is imagine that you've made an order and this is the data that you're giving out so now we have this let's move this in to our next aes app so here we are in our next js application and i just use the create next app through mpx to create this and then just removed everything that was in this return functionality so what we're going to do is we're going to create the serverless function and then come back into this code and display it so that we can see what comes back so if you've never created a serverless function before it all happens inside this pages slash api folder and what we're going to do is create one for get customers and then we're going to create one later to add a new customer so first let's do the get customers so create a folder called get customers and inside of there we're going to create a new file called index.js and now we have this this is where all our serverless function is going to happen but first we need to install the faunadb client so that we can use that to make the request to do that just do npm install and it's fauna db and once you've installed that we can go ahead and start running our functionality here and the first and most important is to import fauna db and that's going to be require faunadb and once you have this we can actually use this to create our query as well as make the request for the query but before we do that we actually need to create a secret and the secret is going to be inside the dot emv file so let's go back to our fauna dashboard and create the secret and then put it inside of our dot emv so here we are inside of our dashboard and you're just going to go ahead and go down to security and then click the new key button make sure the database that we're using is the correct one and you can leave the role as admin and if you want to give it a name that's fine it is optional so i won't do it once you've created your secret go ahead and copy that and drop it into a dot env file with the following name it's going to be fauna db underscore secret underscore key go ahead and save that in there and while we're also here we're going to use versailles to do our deployment so what you want to do is go ahead and log in by typing the word for sale and hitting enter and once you've done that you're going to add this to the secrets to do that type the word for sale secrets add then the same name as you have up here and then the key as well and hit enter and that will be added to their store so that you can use it in the future so now we've done that we're actually going to use that so do process dot n fauna db underscore secret underscore key then we can actually start making our queries so to do that do cons q equals fauna db dot query and that will give us the ability to make queries and then we need to create the client to actually make some of these requests so to do that you're going to do const client equals new foreign db.client and then we're going to pass in this secret right here so just go ahead and open some parentheses and type the word secret so now that we've done our secret our query and our client we're ready to actually do the meat and potatoes of a serverless function now all serverless functions start the same way module.exports and then async request response and then a set of parentheses now every time you make a request this part of the functionality runs and that's what's so special about serverless functions so you can imagine that it's very easy to write a quick query to something and just not have to worry about the function name or whatever you need to call it it's always the same module.exports equals async request response and next.js is smart enough to be like oh you've made a request that this api get customers this is the functionality i need to use and anything above here is going to be used as a variable so i always like to start mine off with a try and catch and the reason is is i want to be able to handle if any errors do occur and the way we can do that is just by doing this try catch and inside of here we're going to write our good path and then inside of here we can write a bad path so first we need to actually connect to the database and make the query so to do that we're just going to say dbs is a weight client which if you remember correctly is the client to the fauna db dot query so we're going to make a query and then we're going to use this fauna db query to actually do the query so dot map means we're going to iterate over every result that shows up then we're going to give it the ability to paginate in case there's many results then we need it to match a query so do q dot match and then inside of that we're going to do a q dot index because we're actually going to use an index to do this and we happen to have one called all customers and all customers is the source that we want to use so once we have that we can then do a ref equals q dot get and then ref and this basically looks up each result by its reference and now we have that we can say okay i have this query what happens if there's a good path so we can just do a status of 200 and then set the dbs data as json and then if there's an error we can do a status of 500 and then we can also do json and say error and then error dot message and then we'll know exactly what the error message would be so just to briefly recrap everything that we've done here now it's kind of tidied up we've said we want to make a query and we're going to use q.map which will iterate over each result then we're going to make sure that it's paginatable then we're going to ask it to match this index of this type all customers then we're going to use that to actually look up each result by its reference and then finally we're going to respond back so let's make the request first we need to import a few things so let's go ahead and import use effect and use state and those are coming from react and as you know next.js is part of the react family it's just a framework over the top so we're going to use these to make our requests then inside of here we need to set our use state variables so let's do data and then set data and we're going to set those to originally just an empty array so now we have that now we actually need to create a request out to call this serverless function and we're not going to do it inside of this use effect which in some standards might be okay because i want to actually use this later on when we add a new user to get the latest data so let's create an asynchronous function and the async function is going to call getdata and that getdata is then going to make a request and that request is going to just make a call to that functionality so we can do await fetch and then the way to call these is to put a slash here api slash whatever the folder name is so in our case get customers and what happens here is it next.js is smart enough to go okay we're trying to make a call to this api and he specifically put this folder structure so api get customers and there will be an index file in here that it can reference and make a request from so now we've made the request we need to handle the data so let's go ahead and say new data and we're going to set that equal to await res.json and then we can set the data in our use date to the new data and once you've done that we can use this functionality anywhere in our application so let's go ahead and use the use effect to make a call to that and we can then look at what is returned from the database and all we're going to do is do this use effect open parentheses and arrow and then here we have our what's actually going to happen and all we're going to do is make a recall to get data and then to make sure this only runs once we need to make sure that this is the ending so two open square brackets at this point we're ready to go so go ahead and type the words for sale and dev into your terminal and then go ahead and hit the default answers to all the questions and once you've done that it will launch on localhost 3000 and let's go and check it out so now we've launched our code here localhost 3000 as you can see nothing is happening here but i have opened the developer tools and you can see that getcustomers has three results here and inside of each one of those there's some data and it has the address first name last name telephone number etc so at this point we're in really good shape we're actually getting the data back from our database but we're not displaying it to the user we're currently looking at a blank screen so let's go ahead install shakri ui and start using that to create the rest of our functionality so here we are back in the code just go ahead and install chakra ui which you can see down here is npm install at chakra dash ui core emotion slash core emotion slash style and emotion theming once you've installed all of those i'll make sure to drop it in the description so you can copy and paste it you can use these to install our chakra ui now once that's installed we can go ahead and start writing more code so what i've done is just opened our index.js and i haven't made any changes yet but let's go ahead and start making them so we have this import at the top we also need to import uh some shakra ui features so let's do heading flex stack box button input form control now this might seem like a lot just to display to the user but i'm actually pre-fronting this so that you're ready to use these for our form that we're going to use to allow the user to create another one so form labels we're also going to use a radio group and radio and that's all coming from the chakra ui core so now that you've imported all of these now we're pretty much ready to go so the first things that we need to do is obviously display something to the user so first let's do a heading and inside of that heading we're just going to do an a an h1 so to do that you do as equals h1 and let's align this to the center as well so let's just put a little padding around it for the top and the bottom and do text align equals center and then we can just type in here something like next js fauna db and serverless now we have that we can go ahead and add another heading here just underneath that says customer data so that we know what we're presenting to the user is the customer data next next we need to create a box around the whole thing so that this is contained and has one div element so this box is actually just a div you can do anything that you can do with a div with this box and now if we hit save we've just got a heading and another heading now we need to do what i would call the table that shows the customer data so let's create a flex element here and that flex element is going to have a margin at the top of 12 which is not 12 but something like for rem and then we can align this to the center and justify it to the center as well so that should line up quite nicely now what we want to do is do a stack and a stack in the chakra ui world is just a way of saying i want all of these to be contained together so they're elements that you want to basically stack one on top of the other so this stack is going to have a bunch of headings here and we're going to just put a margin on the bottom this time as a h4 and this h4 is just going to have the word name and then we're just going to copy and paste these down here and we're going to return name phone number and credit card so phone and credit card and these are the things that we're actually going to return using that service function and actually use so now we have that what we should do instead of just taking this data and dumping it here we should create a component to actually handle this so let's do that so inside of your root directory here not inside the pages but inside this root you're going to create a new folder and that folder is going to be called a component and inside of that components we're going to create one new file and we're going to call it uh customer data.js and this is just going to handle returning specific pieces in a nice way so we're going to import some chakra ui stuff here so we're going to use the word divider stack text and box and they're all coming from chakra ui and that's all we need and then we're going to export a default function here and we're going to call it customer data and we're going to take in some properties here and the properties we're actually going to take in are the same ones we described before so credit card first name and last name and the telephone but let's go ahead and actually return something now so we're going to use a stack but we're going to use a special kind of stack it's called is in line and it's basically going to put them in line instead of stacking them on top it's going to go this way then we're going to take the stack and add a box or a div and inside of there we're going to add a text and the text is going to have a nice font size of lg we're going to add a margin at the top and the bottom of 4 which is the equivalent of one rem and then we're going to add also an mx of the same amount and that could change based upon your your preference but that's just how i how i like it here and inside of that we're going to do a first name and then a space and the last name and that will take care of the first and last name of our customers so now we've done that we actually need to do a divider which we imported at the top here and that's just divide them up so let's go ahead and type the word divider and we're going to add a border of 4 pixels we should add a box at the top here as well because we need to return at least one parent so this box will handle that for us now we need to basically copy and paste this functionality here and do one for our telephone so to do that we're just going to add the word telephone here and remove the last name and that will take care of our telephone and then finally we just need the credit card which we can do the exact same way we can just go ahead and pull this and drop in the credit card so instead of first and last name we'll just do credit card and now we're good to go so we have a first one that will be the first and last name then we're going to display the telephone and then finally the credit card so at that point now we can actually just loop over the data using data.map and present this to the user so now we've dropped back into our index.js file we need to actually import our hard work from the components to do that just type the word import and then customer data from and then components slash customer data now that will give us the ability to use this by mapping over it and that's what we're going to do now so in between our stack and our flex in our code probably around line 46 we're going to actually add in our component that we just created and use that to show our users so to begin with we need to actually check to see if there's any data so we can do data.length is greater than zero and if it is greater than zero then we can actually do something with the code so we're going to map something to the letter d and we're going to use that to display to our user so all you need to do is make a request to customer data and then we're going to use key parts of the return data to display to the user and if you remember we had credit card number first and last name and the telephone so when you're mapping over data you're required to have a key so we're going to set that key to d.data.telephone and that's because i don't know anybody with the same telephone number as somebody else then we can use credit card and we're going to do d.data dot credit card and then dot number because remember the credit card is an object so we just actually want the number and not the rest of the information then we can do first name is equal to dot data dot first name and then the last name is also going to be equal to d data dot last name and finally the telephone number which will be equal to d data telephone now at this point we can go ahead and close out our component here and then outside of these two parameters which will take us to here we want to actually do the other part of our if statement so here we're going to do colon and then open another set of parentheses and say well if nothing else happens and there's nothing to show we'll just put a text here and we're just going to write the word loading and that handles all of our conditional statements and what we should get now if we go back to our website is the data displayed to the user so here we go we can now see that the data has been received from our fauna db we've then used it to sort of create a small kind of table here and it displays the credit card numbers the telephone numbers and of course the names now it's not the prettiest thing in the world but it does give you an idea of how this would work so now what i want to show you is how you can actually insert a new row into the database using a form so that your user for example could create their own customers and then what will happen is we'll actually pull back the data once it's been inserted into the database so just as before we're going to create a another folder inside of this api and we're going to call this one new customer and the new customer is also going to get an index.js file now what we're going to do to save a bit of time and repetitiveness is we're going to take the first sections here and paste them in to our code now you're probably wondering like well why can't you just set these somewhere else as a global variable but we want to treat these as separate entities they can be used anywhere in our application and it shouldn't have to depend on anything else so for the time being it's perfectly fine to recall things that you've already done in your application so i already know that the form data is going to come from the body of the request so let's go ahead and put that in here and then we'll create a db insert based upon that and then we can modify our front end code to add the form so first let's call const form data and we're going to set that equal to request dot body dot data and that's where our form data is going to be passed into this functionality and as before we're going to set a try catch here and the try is going to be fairly similar as before so const dbs is equal to await client dot query and now outside of that everything else gets a little different so using q which remember is the query we can do something called create and you're probably thinking well that's going to create a whole new database but it's actually not the create functionality takes a parameter and the parameter is a collection and you can tell it where you want to insert this data so we're going to tell it we want to insert a new customer into the customers collection and then we're going to pass it in the data that we need so inside of here is going to be a data object and inside of that data object is going to be everything we need to create a new customer so we're going to have a first name and their first name is going to be set to form data dot first name then we're going to have a last name and that last name is going to obviously be set to form data dot last name so so far we have two parameters here now the address is actually an object so what we're going to do is we're going to type the word address here open a set of uh parentheses here to create an object and then we're going to pass in everything we need street so that will be form data dot street address and city is going to be our form data dot city then we're going to create one that says state and that will be form data dot state and then obviously the zip code which is important is going to be form data dot zip code then outside of that we're going to need the telephone number and that will just be form data dot phone number and then finally our last thing is the object for the credit card now the credit card takes two objects here it's going to be credit card and inside of here we're going to create network which to me is the card type so we're going to call that card type and then outside of that the number which obviously is going to be the form data dot card number so we're basically inserting each one of these into our database so now we have that we need to handle what happens if it's okay and then obviously what happens when it's not so we can just set 200 here and we'll just say json dbs dot data and then if it doesn't go well and something bad happens we can set another 500 here and we'll set this to another json and we'll call it error and then error dot message actually let's just change this to e to make it easier and at that point if we save this we can just talk through the whole thing as a whole instead of worrying about typing on the keyboard so we're going to take in the form data and that's going to come from a request body data and that will be our form in our index.js file which we're about to create then we're going to ask it to connect to the database and we're going to ask it to create a collection insert to our customers collection and we're going to ask it to insert all of this data here then if it goes well we'll respond with 200 and return back the data which when you use 400 db will just be a return of the data you just inserted and if it goes terribly we'll just send a 500 back with an error message so that part's covered now we actually need to cover inserting a new customer so let's go ahead and do that so underneath this flex but between the box and the flex we're going to add a new heading here we'll just call this an h4 and we'll add a margin to the top so that it's not pushed up against this part and we'll give this a 6. and we'll align this in the center so it looks nice to the user and we'll say this is add a new customer then we're going to create another flex here and this is going to have another margin at the top of 12 and it's going to be aligned in the center with a justified of center as well so that it sits in the center of our screen then what we're going to do is create a form now we're going to do a form here and the form is going to have an unsubmit like any other form and for now we'll just say handle submit we don't have this functionality right now but we'll add it in a second and then the method is going to be equal to post and the only reason we're doing this is we're going to handle the method and what will happen is if you don't include this is that the query strings will be attached to the index of your file so it'll be like localhost 3000 slash question mark and then everything that we insert in the form and we don't need that because we're actually going to take care of it so now we're going to use something called form control which is just a chakra ui feature we're also going to have a handle change so imagine if someone types in delete types in we want to make sure that we update every time so we'll do a handle change here and then we'll start actually creating the form but before we do that we should talk about these two and what else we have to insert into our code to make it work the way we think so at the top here we have just a state here and then this functionality that has the use effect well we actually need some initial form data that we can then fill in with the names that we want to use so here before anything else we're going to create a new constant called initial form data and it's going to be something called object dot freeze and the freeze is just a definition of the object that we want and it's essentially a way of locking the attributes to it and now we can start creating our objects now this is just going to be each name of the object that we already know about so it's going to be everything in the database first name last name street address city state zip phone number card type and card number which matches what we have in this new customer first name last name address all the address fields telephone credit card network number so i'm going to go ahead and insert them and i won't let you sit here and watch me type we'll just go ahead and time lapse through them okay so now we've typed in our initial form data we also need another state here so let's create a state called const and then it's going to be form data and update form data and we're going to use state and this time it'll be an object so now we have this initial form data and the ability to track this data as we're going along one thing that we do need to do is handle the change when someone starts typing in the keyboard we want to be able to track that and make sure it's correct so what we'll do here is underneath this use will create a handle change and also a handle submit so handle change is going to take a variable e and then we're going to update form data which of course is the name of this part of our state and we're going to do something you may not have seen before we're going to use a spread that's going to take in the form data so that means that we're not overriding it every time but we're only overwriting this particular thing and then we're going to do e dot target dot name and we're going to set this e equal to e.target dot value and at that point this handle change is ready to go so anytime there's a change we'll make sure that we update the target name to the new value the target name will be one of these names here and we'll make sure that they match so they update correctly then of course we need to handle the submit and for now we'll just do handle submit and we're going to take in the e again and we're going to do e.prevent default and then we're going to do an add customer method here now the add customer method is essentially going to take everything that we have and pass it down to our api functionality that we created over here for our serverless functions so what we should do is create that functionality because we already know what's going to happen but we can wait until we actually have a form to test to make sure that it works so now we've created the handle submit and obviously the on change handler we now actually need to create this form so inside of this form control we're actually going to do all of our work now what's great about shaker ui is it basically takes care of everything for us so let's go and create each part of our form element and then let's try creating a new customer so each of our input fields that are text based are going to be all exactly the same so to do that we're going to do a form label and inside of that form label is going to be the html for and then equal to whatever we want to call it so for this this is going to be first name and we're going to set this to first name and now we have the label then we actually need to do the input and the inputs are fantastic with chakra ui so you type the word input type text name equal that to first name id equal to first name as well and then we can just throw on on change and we'll do handle change and that's all that we need so we can close this out and our input is now complete we can actually just copy and paste this and make this our last name as well as our first name so let's take the form label and then just hit enter here and then change everything that's first name to last name and then we can just change the actual displayed part to the user and now we have an input for both first name and last name and now we need to do the street address so we can take the same form label again copy and paste it and do street name so we'll do street address here same for the ids they're going to be street addresses and then the on change obviously will be handled the same way now before we go any further i just want to just talk about again that on uh on change handler here so we go back to it you can see that we're actually looking for the name and then we're going to set that to the target name so as long as this name here matches the name in our fields we'll update it with the latest date and that's how we're going to do all of our form pieces now the next part is city state and zip code and usually on a form they're all in the line so we can do that by using the stack functionality of shack or ui here so you just type the word is inline and it will make it inline instead of stacked on top of each other so now that we have the stack we can just use the same again form label here and use that to create what we want so first let's change this to street address before we forget and then we can take this form label drop it in here and say this one will be our city and now that we have the city we just need to do that again for zip code and for the state so i'll just go ahead and time lapse that so now that we've done that now we just need to enter the phone number so we can just create another form here with the exact same thing we're going to keep it as text so that it could be a free input field because we're not going to do any form validation here even though you should and i encourage you to do that we are going to do it for this crash course now we need to have the user show us what kind of credit card they have and instead of making them type in visa or mastercard or amex we can just use a radio button to handle this for us so we can do a radio group here and we'll give it the name of card type and we'll just add some margin around it and we'll also add some spacing in between each radio button and finally this is also going to be inline so it will be across the page and then each radio button is going to be the word radio it's going to have an on change handler just like everybody else and then we're going to give it the name equal to visa then the value will also be visa and finally the label will also be the same the way that this works this name is going to be passed when you hit form submit so that will update that based upon that now obviously the unchanged will flip-flop between which one you select and then the value will be passed down to us so you can just copy and paste this radio button there's nothing special about them they just need to be changed so we need three of them total so we have visa then we'll do one for a master card we'll do one for amex and we'll call it american express and then the final thing that we're going to need is the card number so the card number we're actually going to do is slightly different we're actually going to make them type in a number so you can go ahead and copy one of these input labels here and drop this down outside of this radio group it's going to be a type of number and we're going to call this card number and we're going to ask for the card number and then we just need to make sure we update the name and the id and then the only thing left to do now is of course have a button that actually does the submission so underneath the last input but in between the form control we need a button and we're going to make this a type of submit and then we're going to add an my which is top and bottom margins which we've used previously and we'll also add an ml of 20 then we'll just make the width 50 percent of the parent and the size will be medium and that will add some just styles and heights and then the border we can just set something like two pixels and the border color we can set equal to green dot 500 and we'll just say add customer so as you can see now we have a form at the bottom of our page that we can use to input some data so let's go ahead and do that so here we have steve jones 123 main street and his number is 555-555-5555 then we have a visa card and we'll just add some numbers in here and now if we hit add customer we should see something happen so let's go ahead and try and that's exactly what i expected to happen we got all the way to the add customer but we haven't implemented this function yet so let's go back to the code implement the function and then go from there add customer functionality is going to work is essentially we're just going to pass in a bunch of data to it and that's going to be from our form function is here let's create another one and we'll call this one add customer and we're going to do an await fetch and we're going to do the same thing as we did before right api slash and then whatever the folder name is so here it's new customer and now we need to actually send some request options down now if you've never done a fetch with a post we're going to need a few things so just underneath our form data here we're going to create another constant and it's going to be our request options i'm going to set the method to post we're going to set the headers and the content type here is going to be application json because we're going to send it json down and then finally we need to actually send something in the body right so the body is going to contain our form data so to do that we're just going to do body and i'm going to do json.stringer5 and then data form data and then we can take this send this down so we can just go comma request options and then we can do then and then say after we've done that go ahead and get the data because we know it's successful so go ahead and get the data and then if not catch the error and we'll just log there out so now let's go ahead and flip back to our website and see if we can now submit a form so let's hit f12 and let's see what happens and as you can see up here steve jones has now been added so let's go ahead and clear that out and we'll add somebody else how about if we add tom jones and tom jones's phone number is eight nine eight eight nine eight eight nine eight and he lives now in i don't know mystic which is also in connecticut but i have no idea what the zip code is so let's do that one and we'll change this credit card number here too and there you go tom jones has now been added to our database so there we go guys next.js and 400db working together perfectly so we had a form at the bottom to add a new customer using the collection of customers and then we also had the table at the top that presented any new user that we had if you did enjoy the content make sure to drop it a like hit subscribe because i'll be dropping more content like this in the future and of course don't forget that notification bell until next time see ya
Info
Channel: James Perkins
Views: 5,310
Rating: undefined out of 5
Keywords: NextJS Fauna, FaunaDB, NextJS FaunaDB Crash course, NextJS Crash Course, FaunaDB Crash course, NextJS Tutorial, FaunaDB Tutorial, next js, web development 2020, web development full course, next js tutorial, nextjs deployment, NEXTJS + FAUNA CRASH COURSE, serverless
Id: mEc9u231jFM
Channel Id: undefined
Length: 49min 18sec (2958 seconds)
Published: Wed Oct 14 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.