Intro to React Database Connections [Sync Data to Your React App]

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] how's everybody doing um my name is nico i'm a software developer here at headway um i see a lot of familiar faces so thanks for coming back um so so so today um i'm gonna so we've gotten a lot of feedback from the past meetups uh on kind of how to how to uh continue with this kind of down this path with uh react for some of the folks that are getting started and um the most kind of the most common feedback we get is how do we turn this kind of toy app toy create react app into something more than that right so how do we go from all right i've done the the to-do list tutorial how do i actually start to build something real like something with users or like just start to kind of make this into a more robust thing as someone who just knows react right um so yeah so that's kind of uh when we got uh together here at headway we decided that the best path forward is just kind of start doing these kind of piece by piece talks and kind of build upon each other build up on the last talk so today we're going to explore kind of the very beginnings of what it's like to interact with a service outside of your react app right so how do we actually store data fetch data from from somewhere that's not our own app um so talks called reactan and databases and um um we um i want to show so what i did is for those of you who were um with us in the last talk we built this to-do list app using glitch i've actually moved that code base over to this code sandbox environment which maybe you saw if you were at the testing talk uh a month ago so chris held used this and after talking to him i decided this is where i think we should do all of our future talks on so i just want to walk through this app real here so a lot of you will be familiar with this this is the exact same codebase we built except i've put all the components in this in this folder here uh the form the title and the to-do and um yeah so i've kind of initialized the to-do's here in this this initial data array and i passed it into the todos here right so we we are just kind of a standard to-do list app and um the only thing that's missing so i'm just going to show real quick um just i'm just going to do an example right so i can submit i can delete right so we have kind of the basic functionality here but the second that i refresh it goes back to the to the initial data right so this is kind of where a lot of people kind of say all right what's next right so i have some state i know how to manage it and how to update it but how do i actually build something right so um what we're missing here is just kind of an outside database right um so we all know what a database is kind of in the abstract right um essentially just a collection of information that's easy to like access and uh update right uh but from react like we don't really i mean we know what it is but um if you're if you started as a front-end developer it's kind of a um kind of an a strange subject if you are not familiar with it so um in order to be more productive or like to start to tackle this stuff um we're going to touch upon a couple of like non-js stuff just to know as we move forward as we start interact with some of these um outside things so i just want to go over real quick for for those of you that don't have any experience with with databases i feel like a couple of things will go a long way here today so um when we talk about databases um i'm going to do a lot of hand waving just fyi just to kind of fill some of those gaps there's essentially two types of databases relational and non-relational very high level right i just want to talk about the two types real quick relational or what most of you think of a database think of it like as an excel sheet right just tables and rows and most of the databases that you are familiar with or that you use are probably relational relational databases use sql as a query language which is kind of for those of you that have used it it's like the select star from language notation and as different companies so sql is like a standardized language right and as different companies started build software to kind of wrap this language uh this kind of the raw sql database and make it easy for users to access it um they're they're starting to kind of like different dialects started to arise from from from that standard of sql and that's what we now today know as like postgres sqlite mysql these are all uh um database management systems that implement sql but there's kind of different flavors of the same thing and that's kind of it's essentially the same thing but just kind of a different flavor of the same standardized language uh so that we're all pretty familiar with um the other one is non-relational databases which are usually referred to as nosql this one these are haven't been as common but they're kind of they have been on the rise for the past like five ten years and there you can think of it as like kind of big json objects um so uh they're like schema agnostic so they don't you don't need to have this kind of metadata blob behind it before you start to push things up to the database it's kind of it allows unstructured data to be stored and manipulated kind of on the fly really quick so this is very popular with now with startups that are moving fast they don't really uh the overhead of kind of planning out the entire kind of data model of the whole company before they even push like that is a pretty big overhead and they just want to kind of get going quickly and start to push things up so um you might know some of these um there's kind of multiple types of them there's key value stores like redis and dynamodb from amazon are the most popular ones those are essentially just like key value pairs so you just literally just have a key and a value the database doesn't know what's in it except for the keys and it has no idea of what the values are just notes this is the key and what's stored there and it's mostly useful for like when speed is the top priority right you need to kind of fetch something really fast document stores are the other type mongodb and elasticsearch are the most popular ones these are like semi-structured so there's kind of a pretty flexible structure but still json form and even though there's no tables you can still the database does know what's in those values so you can query by you know some of those values and then graph databases are another type of non-relational these are neo4j is the most uh popular and amazon neptune is the one uh big one they represent data as like a network of nodes obviously if you're familiar with graph theory it's kind of it facilitates visualizing kind of graphs most um big tech companies kind of keep like social graphs and uh consumption graphs like payment graphs to know kind of uh what you're spending on um tracking kind of your individual spending behavior um so yeah so just want to go over that real quick um so i'm gonna go back to our to-do list real quick um so the question here is all right so which okay so we know like all these like all this there's many many types what should we actually use right um well we can spend some time kind of setting up like a database management system or setting up like a server and like all the models to interface with it or we can just um use like a simple document store and get started that's like we talked about right like um when you don't really want to set up your entire schema beforehand you can use a document store and get started pretty quick so um that's why i decided that we can use something called jsonbox which is a it's a service that essentially uses mongodb under the hood mongodb is a document storage or like a a document store service a nosql document store and this is a really nice service that um essentially the second that you go to jsonbox.i io a database is created for you this endpoint here is essentially a random hash that gets created every time you go and this is now kind of our our database endpoint i can go to the dashboard here and show you kind of how it works so um this is essentially a rest api as a uh nosql document store so what that means is i can create read update and delete uh resources here really really quickly so this gives me like a little playground to make http requests to my endpoint so just to get started i'm gonna i'm going to look at kind of i'm going to try to build a to-do in my in my endpoint so i'm going to go back and i'm going to look at what a to-do looks like and it essentially has an id and then text right so the id will be created for me i'm just going to send an object a document with just text in it i'm just going to call it first to do and um i'm going to post it to my endpoint right i'm actually going to call it first document and then this is what i get back as a as a response so it it now has an id and i created on right so no schema nothing just just a document that's in my in my store i can um just to show you i'm gonna actually now i'm going to do a get to this endpoint and what i get back is an array with this document in it right so i can now retrieve it um i'm gonna create uh so like a cool thing that you can do here is for example um i can group uh i can create a a collection of these documents by simply adding a um kind of the collection name to this endpoint so i'm going to do to do's and i'm going to post instead of document i'm going to post to do so when i post it the return is again the document i just created when i do get to the to-do's i just get the ones that are in my collection if i remove the to-do's from here i get all of the things right so you can already see kind of how you can sort of group these documents super quickly right um let's see um i can create i'm gonna just create another one here and the to-do's i'm gonna do second oh sorry post all right and then if i do get to my to-do's then i only get the the two that are actually to do um i can so that's i can now retrieve and i can create i'm going to do an update to one to one that's already there in order to do that i do a put request to the to-do's and then i have to include the id of the one that i want to update right so i'm going to copy the id of the second to do and i'm going to paste it here at the end and then i'm going to do second to do updated and then i get this message saying record updated right and if i get again not to that one but to all of them you can see that the second to do was updated and i it now has this updated on flag so the the store is kind of doing some things for me in the background right and finally the delete uh works just like put i do the to do slash and then i'm gonna quickly put this at the back here and record removed and just to double check i'm going to get my to do's again and i only have the first one all right so that was just a super quick overview of what a document store looks like and it works right so all right so we can do this here but um how do we actually get this how how do we use this from our from our react app right so um let's move over here and um the first thing we want to do is i guess we're going to use the same endpoint that we just created so we have one thing in in here right now so the first thing is i'm going to remove the initial data for now since we're not going to be using any initial data we're just going to be using our store and i'm going to change this to just an empty array for now um and uh the first thing is we need a way to actually make these http requests from our our react app um there is a really nice library to do this called axios that we can add as one of our dependencies here so for those of you that haven't used axios it's a access is a promise based http request library um so what i'm doing here in ad dependency that's the same thing as like doing an npm install in in your local machine so now it's in my is in my package.json now and i can import it in here and the way that the x shows api works what i want to do is as soon as the app kind of starts up i want to call for my to-do's right so let's make that function that actually does that right so let's call that function fetch to do's uh and uh i'm not sure exactly how it's gonna look yet or what parameters it's gonna take but what i want to do is i want to fetch using axios so let's just do i'm just going to do the response is going to be and then the way that axios works is i just call access.get and that is going to make a get request to the url that i provide here so we've got to put our endpoint which is this whole thing right and let's see so this response here is going to be whatever comes back from from this right just to actually see what comes back i'm going to just console.log it here so we can actually see what that looks like all right so okay so when when do we actually call this function right so we have this function but how do we actually call this when the where the app renders right so um if we we're using a functional component so react actually gives us a if you were familiar with react before the component life cycle methods um this this uh fetching data on on render is considered a a side effect right so it's something that we run when something else happens or it's not exactly the return value of this of this render function so um i'm going to include uh use effect which is the thus the side effect hook and react and how that works is it's a it's a function that runs when something else happens so i'm going to show you what that looks like so use effect takes a function and then it takes what's called a dependency array which tells it when should i run so that function that we're going to pass it is simply an anonymous function that just fetches the todos right that's all that it's going to do and we want it to run only once on mount right so in order to do that the dependency array is going to be empty so usually you would use a use effect when say a boolean value flips from true to false or when something gets populated uh the the variable that goes in here is that thing that you wanted to kind of uh fire on but in this case if we do an empty array this use effect is gonna run as soon as the component mounts um so let's see so i'm gonna so i just refreshed here and this use effect ran and we got something in our console that we console logged here so let's see what that looks like oh so we got a promise that's pending right so this means that the return value uh or when we console log this response this axios is a promise-based um library so we actually have to await for the promise to get resolved so a wait is a keyword in javascript that stops the execution of this function until we get the response back from the database in order to use a weight you'll see though a syntax error here that says that you cannot use the keyword awaits outside of an async function so we actually have to wrap this we have to preface this function with the async keyword which ensures that this function actually returns a promise um so async if you're familiar with promises this is kind of the new implementation of or this is a solution for the kind of the callback chain or the callback hell as they call it where you're doing that then.then then forever so this allows for this function to actually stop its execution wait to get resolved and then we and then we're going to console.log here so you can see now that after refresh we're console.logging this object that has a couple of properties here data is one of them and in the data we have an array with one thing in it and that thing is our first to do right all right so now we have data in our app so let's actually use it so um instead of console logging i actually want to set the to-do's to this data array right so if i do set to dues to rest that data refresh here all right we got our first to do from our database in here right but let's actually let's let's make this a little bit less so what i'm going to do is just to just in case that there's a bad response from the from the api or from the from the document store i'm going to destructure this response object into the data and the status was it believe so so what this means is i'm going to pull these two values from that response object so here we can now just do data but if the status is so let me just console.log that object again just show response one more time so response had a status of 200 right so that's 200 means everything went okay so we're actually going to use that status to kind of before we set anything we're going to check that status so i'm going to go ahead and do data and then status and i'm going to only set the to deuce the data if the status was equal to 200 right all right and it still works okay so all right we got to the first piece here right so all we're doing is just fetching on mount or we're putting it on here okay so um the next step would be um or just a little bit of cleanup here i don't like this like ugly string here we're going to be using this also when we actually go and and delete something right so i'm going to uh turn this into a variable up here and just call it that point right that's going to be our endpoint and then here i can just do endpoint plus to do's that's just still work right um just so usually so this is technically kind of a private key right because this determines your unique database in json box so you know i'll i'll make an exception but usually this we would want to hide in some sort of environment variable right if you're using react so actually create react app has a environment variable the ability for you to set environment variables built in if you preface them with react underscore app and then you have your your key so um i can actually show that real quick so i'm going to create a m file and i'm just going to do json box key oops and i'm going to paste that private key i'm going to paste that in here and ideally you you would put this that end in your git ignore so it doesn't get actually saved anywhere right that's the reason for this so that it doesn't get kind of saved with your code and in here i can just do and this you'll be able to do this as well in create react app i can just do process.n dot json what was it json box g uh let's see all right sorry what do you mean parents no not am i yeah let me try this maybe i had to save the that end that's probably what it was all right well maybe i'm missing something here but um should work anyways sorry no that should that should have worked i tried it earlier but maybe there's there's there's something that i i must be missing here but yeah i tried to wing it didn't work um i'm just gonna get rid of that for now but you get the you get the idea right it's just you don't want to have those things kind of in your source like that so i'm just going to copy that again here and all right okay so um the next thing here is um handle so let's let's change now our our handle submit so that we actually can create some new things right so right now our handle submit is just trying to get this just right there we go our handle submit is checking if the input value is empty if it is it just goes to next if it's not it creates a new to do and then it sets the to do's right so uh what we want to do for handle submit is uh make a an axios request right so i'm gonna i'm gonna comment this out here for now and what i wanna do so the handle submit runs when i click submit with the values in there right so um i'm going to do the same thing that i did uh in the um in the use of in the in the fetch to do's i'm going to do i'm going to wait for the response and i'm going to do axios instead of get i want to do post and how post works is it takes the end point and then it takes the payload right so my endpoint is going to be endpoint and we're going to post to the to the to-do's and then my payload is going to be essentially the input value in the text and that's it right so that's really my payload um i could do i could just make a i mean i can just do like and then uh input value and then i'll just do my new to-do is what i'm sending over and then uh this should come back just like just like in fetch to do's it's gonna come in this format right the kind of http request default format so it's going to have a data key and a status key so i'm actually going to just knowing that it's going to be that it's going to look like that i'm going to break it out beforehand here and let's just do a console log or actually let's just uh the data that comes back if you remember is going to be the new to do right so what should we do here right so we have we're going to get back the updated data should we should we push it into our current state should we fetch again and just kind of get a fresh uh kind of the fresh version of our state right so just to keep things simple let's just since it's going to be updated up in the server let's just as soon as we get back a successful response let's just re-fetch the whole list and we'll just re-render it so that means is if the status is 200 meaning the update was successful uh let's just do the fetch to do's again right so that's going to run that function that re-grabs the whole thing it might not be the most efficient thing but it kind of saves us from like doing all this internal state uh calculus that right now might be simple but maybe later on where we're trying to keep when a bunch of things are changing at the same time it might be a little more complicated right so so let's see if that works right so the data is not really being used right now right all we want is the status if it actually updated successfully so i'm gonna go and do let's try this right second to do i'm going to submit it oh did that work let's see yeah that's exactly what happened right so this handle submit function um needs to be async right because we have to we actually want to wait for this to actually be successful before we fetch right so you see how we refreshed it and it was there but when we actually called fetch it wasn't there yet right so let's try that one more time i'm going to do a third to do and now when i hit submit it's coming in here right so we see that they're coming in like they're being successfully submitted but they're in the wrong order so um we can actually uh in our fetch to do's let's actually sort these when we fetch them so um we can actually include a sort parameter in the url so i can just do when we fetch grab them and then sort by and if we go back here i want to sort by the created on right so i'm going to copy that key that's what i want to sort on so now they're in the right order right so if i if i add a fourth to do here it's not being added at the bottom right also when i submit i want to get rid of this so um i'm just going to add here to the handle submit if it's successful also set input value to an empty string right so that clear that out just to check that fifth to do all right [Music] so the last thing here for the um for our app is the handle delete so this is going to be very similar right um all we want to do is just we want to do we're going to get the response we're going to wait for axios and the method that we use is delete and we delete uh delete is a little bit different so remember when i was showing you the different uh uh methods here to delete we actually need to put the id at the end of the resource name so we're gonna do endpoint plus slash to do's slash let's actually change this to uh and then we're gonna do the uh the id that is coming from here right and yeah we're getting the syntax error that we cannot use await so we gotta this has to return a promise and essentially uh from the delete we received just like a message that says like resource was was deleted so the response is useless we just care about the status right so the same thing if the status is 200 i'm just gonna refetch all right so let's see if that works all right cool so um just to show you so you can actually have multiple document types living together in this same document store right so so to do's they all follow the same kind of structure right but i can have i can create another endpoint that we group these documents together these are going to be users now right and i can just have you know first name last name you know just an example right uh and uh these are independent right of my to-do's in terms of my my store right now right they're on a different endpoint they're grouped in a different collection so so you can see kind of the benefits of this right we don't have any schema we don't have any structure we're just kind of to get started it's uh it's pretty great um yeah so that's kind of the idea uh or kind of kind of the power of of this uh type of database right and this still works just fine it still just gets my my to dos right so um i'll leave the the put or the update as uh as homework uh so in our previous task we we didn't cover the updating locally so um that's not too hard to figure out so i uh challenge you to give it a try yourself implement that locally and then actually implement it in a using the api so um obviously so just something to keep in mind is i'm gonna just walk through the real quick too it's like um in a in a react app you would you see how your api logic is kind of spread around everywhere uh you have these kind of these endpoints everywhere so um what you would want to do or kind of the best practice is actually just keep your create kind of like a module for your api and kind of use that kind of like higher level object to actually make your query so we have a few minutes i'll show that real quick here if you i'm just going to create an api.js file which is going to kind of handle all the api stuff so that i don't have to think about that um so i'm just going to move the endpoint there right so my app doesn't need to know what the url is i'm going to move axios there and i'm actually going to just get a [Music] i'm going to create a quick let's see i'm going to do this api is going to export an object that kind of has like a nice wrapper for me to kind of call on this stuff right so the first method here that i want to do is let's see let's actually put it up here so i want to be able to just say create and have it just make it so the create i'm going to pass it a new to do and what that's going to do is it's going to just return the actual like the oops the axios create that we had right so this is what i want my create function to do [Music] return okay and what i'm going to do is i'm just going to export create as a function same for these other ones here so i'm going to refactor this one to just await that create so i'm going to do import api from api.js and it's just going to do api dot create and all it needs is the to do right and it's so you notice how i'm i'm just returning the uh so this function isn't async it's just returning the promise that axios is going to give back right so i don't need to to async await here this is going to return a promise i'll just async await it over here right and the return value is the same it's just a different uh interface with this thing so i'll do the same for the for the for the i'll do the same for the get so i'm gonna do let's just call it get all because in the future we might have get a specific one right and this one's just gonna do return what was it oops this and this will export it over here so now here we can just do await api dot get all we don't have to worry about anything else our api is the only thing we don't need to know about what is in there right from our app and finally this one we'll do real quick just going to do destroy because delete is a reserved word so i just need the id and then just return that all right there we go and um yeah so that's kind of how all right so did that refactor kind of did you get the motivation behind it just kind of from your app.js you wouldn't want to know about endpoints or anything right you want to create kind of this module that handles all of the http logic and all that stuff so yeah that's um a very quick so and if you had your api would obviously talk to other resources so um you could do something like you know i would want this to just be for to do's right and then from your api it would be uh let's see you would do right and then your api could actually have kind of a name space for each resource you have right and this still works for everything okay so i know i'm running out of out of time um so next steps right so json box is nice right but nick uh jason box is somebody's side project obviously doesn't scale do not use this improv it is backed so it is a mongodb database and kind of the easiest way or like a very easy next step um sticking with kind of this architecture would be to use something like firebase right so firebase is another document store um that's super easy to set up i've actually um i've linked to a really really good firebase starter video that i used a few months ago to get one of my side projects going um there's this guy called max he's from germany and he's like the best youtube person like on earth and uh he just is like a firebase guru and uh his starter video is like the best one i've ever seen um but yeah firebase is very similar to this there's some local config that you need but it's essentially very similar to this you're just kind of pushing up docs and pulling down docs based on the collection that they're in and um let's see what else i got um i i'm also linking kind of a more deep dive into the async await and promises which i think is a very important concept when you're dealing with kind of outside services so it's very important very easy to get tripped up and just getting just like a basic understanding of how they work and kind of the different states that it can be in will save you a lot of headaches as you're working through this stuff and i'm going to include some code sandbox links kind of the different the three different steps so at the beginning kind of where we left off um and then before we refactored into the api js and then after so i have three code sandwiches there if you kind of want to do it yourself again or just want to kind of take it to the next level but yeah that's all i got i i hope that that was kind of a you know just a 101 on how these things work how you would actually organize it and hopefully this will kind of push you to keep going and you know keep making it more real every time right so yeah that's all i got thanks you
Info
Channel: Headway
Views: 75,039
Rating: undefined out of 5
Keywords: react tutorial, reactjs tutorial, react tutorial for beginners, react tutorial 2020, react database, fetch data reactjs, data flow in react, firebase with react, firebase react, integrating firebase with react, reactjs tutorial for beginners 2020, nosql database, nosql tutorial, nosql explained, nosql database tutorial, js promises, async await javascript, database reactjs, firebase database reactjs, react firebase storage, react app, react js, react mysql, react sql
Id: HVdMhKN2ng4
Channel Id: undefined
Length: 45min 47sec (2747 seconds)
Published: Mon Jun 15 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.