React User Login and Authentication with Axios

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
today we're going to create a react login form that uses axios to submit user information for authentication our form will keep accessibility in mind and deliver success or error messages let's get started [Music] hello and welcome hi i'm dave today we're creating a react login form that will use axios to submit user information for authentication our login form will also keep accessibility in mind this tutorial is more intermediate level than it is beginner ideally you will have already completed my react js for beginners course or a similar course for getting started with react we'll just keep moving and i'll share a link to the source code in the description and if you like the style and pace of this tutorial make sure to like the video and comment below so i'll know to make more like it okay i've got visual studio code here on the left and on the right i've got an example of what we're creating today running in the chrome browser now in the functional app component notice that i've already changed the default divs that are in place when you create a functional component with main elements i prefer the semantic element and right now i've got a register component here because that's what i created in the last tutorial and hopefully you've watched that you'll get a little bit of deja vu today because a sign-in form is a little bit like a register form but there are also some key differences so besides having the register component here we're just going to end up removing this because we're going to create this sign in component today so over in the file tree we'll just add a new file and we'll call this login.js now in the login.js we'll create a functional component and so i'm going to do control alt and the letter r you might be able to just type this right into the file but i do underscore rafce and there's our functional login component now that i've saved that i'm going to jump back to the app component and import it while i'm thinking about it and that would be from login and now inside of here i'm just going to replace the register with the login for now because that's what we want to see today we can close the app component and i'm also going to press ctrl b to hide the file tree because we're really just going to be working in this login component for most of the time today so at the top we need to import some of the hooks we're going to use so we'll have import and now we're going to import use ref we'll import use state and we'll also import use effect and those will be from react after that we can come down into the component and i'm just going to paste in a couple of things we've got a couple of refs that we're going to create in reference in our form we've got a user ref so we can set the focus on that first input when the component loads and we've got an error ref because we'll need to set the focus on the errors especially for a screen reader to read or other assistive technology if an error occurs now underneath that we're going to put three pieces of state and you can see here we've got a user a password and an error message the user and password of course correspond to our inputs and the error message corresponds to an error that we might get back when we try to authenticate and finally one last piece of state and that is going to be success and of course set success and that is just for this tutorial really it's going to let us show a success message in the future as we tie all of this together we would replace that and navigate with react router to a page of our choice after we have had a successful login okay we're going to apply use effect twice the first time it's going to be to set the focus on that first input when the component loads as you can see there is nothing in the dependency array so this will only happen when the component loads and we're putting the focus on that user input that we will reference with the user ref and the second time we use the effect or use effect i should say we're going to empty out any error message that we might have if the user changes the user state or the password state essentially if the user changes anything in either one of these inputs will make the error disappear because they've already read it and they're making their adjustments okay i'm going to scroll up now we're ready to work on our jsx for the form and i'm once again going to replace the div with a section element i prefer semantic elements whenever possible so now that we have a section element inside of it the first thing i'm going to paste in here and i'll press alt z so the code wraps is our error message display so it will just be a paragraph element at the top of the section and this could display any error message we get notice the aria live attribute it's set to assertive this will have a screen reader announce this message immediately when the focus is set on this paragraph and that's why we have the error ref so we can set the focus there and then notice i've got a class name and i'm not going over the css in this tutorial but if you want to take a look i am including it in the source code okay after the error message we need to add a heading for our page and i'm just going to call this sign in like we see over here on the right here's our sign in heading and now we can begin our form so with a form element added we can remove the action attribute though we will not be using that today inside the form we're going to have labels and inputs for the most part so let's start with a label as every input should have one notice we automatically get the html4 attribute it will need to match the id attribute of the input i'm going to put user name here and likewise inside the label i'm going to put user name and now we can add an input immediately afterwards and i'm going to put a colon and t and we should get a text choice there we go and now this is a text input for username and it automatically gave us a name attribute and an id attribute i'm not going to use the name attribute like i would when i traditionally submit a form i am going to use the id and i'm going to put all of these attributes on separate lines so we can break them down and i won't have as many attributes if you've completed the register form tutorial that i had as i did for the register form but we will still have several and this needs to match our html4 so there is the id attribute this is type text after that let's go ahead and apply that ref we created so this should be the user ref so we can set focus on this input then we want to set auto complete to off this is a preference but i would prefer not to fill in the username with past entries and that's what autocomplete would do otherwise and then we want to set on change and here we'll have an anonymous function and inside this we will tie this to the user state with e dot target dot value and now we're gonna add one more attribute that we did not add to the registration form but you sure could go back and add it if you want to and that's the value and now we'll put the user state in here and this makes this a controlled input now this is important when we want to clear this form and you definitely want to clear a sign in form i believe in the registration form tutorial i said i'll leave that up to you but this is crucial if you're going to clear the inputs upon submission and then let's add the required attribute because both of these fields will be required and that's all of the attributes that we have for this input now in the registration tutorial i added some aria attributes we had an aria valid and or invalid i should say and then we also had an aria described by but that went along with the validation and it described what was required of each field we don't really need to give the user hints about what we require here they should know their username and password and if they don't we don't want to provide any assistance for somebody trying to gain access that should not have access okay i'm going to highlight this label and this input and then press shift alt and the down arrow and we should get a copy of our username label and input and we did and i'm going to change some things now we'll select username with control d in all three spots and i'll type password now that makes me want to go ahead and change the password here to a capital p but otherwise we could change all those at once this is not type text though this is type password as well and that's important so when we type in this field we don't see the text we should get dots that hide what we're typing the autocomplete attribute is not necessary it's not supported by the type password for input and now for set user we want to change this to set password and our value should be the password state as well and then we can go ahead and remove this reference we're never going to set the focus directly on the password field so we didn't create a reference for it and those are all the attributes we need for the password field okay i'm going to scroll up a little bit so we have some more room and underneath this input i'm going to add a button and for the button text i'm just going to say sign in just like we see in our example here to the right now we don't need to add an on click here because it's the only button in the form so instantly when it's clicked it triggers a submit event so we will want to handle that submit event with the form but while we're here at the bottom of the component i'm going to paste in our need an account sign up link here and i'll save so it formats correctly there we go now there's a note here that this would be a react router link so this is just a placeholder link that says sign up should lead back to the registration form now this will give a warning when you launch your react app right now because this is just a placeholder link but we would replace this with a react router link when we pull it all together okay scrolling up to the top of the form we need to add the on submit handler so we'll say on submit and set this equal to a handle submit function for this component but we haven't created the handle submit yet so we need to do that i'll go ahead and scroll up and i guess i scrolled too far let's put it right under this last use effect and we can define handle submit this will be an async function it will receive the event and then inside the first thing we want to do is use that event to prevent the default behavior of the form which would reload the page so with that complete i'll save and i'd like to point out we don't have to pass the event to the handle submit function it receives it by default we just need to specify it here as we define the function and our event dot prevent default will work now this is the part of the tutorial where we need to integrate axios and some global state for our auth which is where you should probably store your authentication but first if you were just interested in creating the form and you don't have a back end in place like we've created in my node.js for beginners course that tutorial if you haven't completed it for example we could just put a flag in here and this allows us to go ahead and set the success and we could set success to true and now no matter what you entered you could see the action of the form so let's go ahead and log the user and the password here as well and i'll also add that we could clear out those components and being controlled components with the values now when this is submitted it would instantly clear those components since we know this will work let's go ahead and add the little bit to our jsx that will respond to that success so underneath the return i'm going to paste in some code and you can see i started a fragment here and then i'm checking the success state and if we have success we're going to show this section element instead which says you're logged in and has another placeholder link here that says go to home and then for the rest of the ternary statement if essentially success is false then it would show our form so we just need to close off this ternary here after the section so we need a parentheses and a curly brace and then we need to close out the fragment and if we save we should get a little reformatting there but now everything is in place to test out the form we've created so i'm going to remove the example form and we'll launch the current form that we have here in our code and to do that i am going to open up a terminal with the control in the backtick and type npm start and we should see our project now launch in the chrome browser okay and there's our project we also have the warning in the terminal that i mentioned due to those placeholder links but that is not a problem right now so let's close the terminal i'll close our previous example and now we're working with the code we've just created to test this out i'm going to expand chrome and then i'm also going to press ctrl shift and the letter i to open up dev tools and we'll just test out our form to see if everything is working so far as we expect i'll type password of one two three and yep we've got dave123 and our success page is also working that says we're now logged in so i'll go ahead and close the console and reload the app and we're back to our sign in and now i'll resize the browser and we are ready to add our global auth state okay i'm going to expand visual studio code now so it takes up the entire window and show the file tree inside of our source folder i want to create another directory i'm going to call this context we're going to use the context api and then inside this context directory i'm going to create an auth provider dot js inside the auth provider we're going to import create context and use state and after we have our imports there we go i'll go ahead and define our auth context we're going to set that equal to create context and then we put an empty object inside now we want to export const and then say auth provider as we create our auth provider and inside of the auth provider weight i need parentheses first then we destructure the children and the children will be represented or children actually represents the components that are inside of the author provider or nested inside and i do cover the use context api completely in chapter 21 of my react js for beginners course okay inside this auth provider we're going to create some state here and it will be auth and set auth and we'll just set this equal to use state and this will be then object as well and now we're going to return and here we'll have our auth context dot provider and now we can set the values that we are passing for that context and here we'll have our auth and we'll have our set auth and now that we have that we can close out the auth provider and there we get the closing auth provider and inside the auth provider you have the children which once again are the components that would be nested inside the auth provider after that we just need to set our export default and this is the auth context notice it's not the auth provider so we've got two separate things here auth provider and auth contacts okay we can save this and then i want to go to the index because we're going to provide well this provider is going to provide context for the full app so just inside of the index is where i want to import this so here i'm going to import the auth provider and this will come from dot slash context slash auth provider there we go so this needs to surround the app and everything in the app will have access to this context so here we just say auth provider and there it is right away and i'll go ahead and just press return cut the app component and paste it inside and save and that's the only change we really need to make to the index okay let's close that and we can close the auth provider we've created and now back at the login i'm going to hide the file tree again we need to also import use context and after that underneath we're going to import auth context which again is not the same as importing the auth provider that we put in the index.js so we've just created a global state with use context for our app and so now let's go ahead and pull in what we need for our login component and that is the set auth so i'm going to say const and then set auth and we'll use context to do this so we set it equal to use context and now we need to pass in our auth context so you see why we needed to import that as well and now if we successfully authenticate when we log in we will set our new auth state and store it in the global context okay we're going to save the login and i'm going to show the file tree once again because now we're ready to bring in axios and there's a couple of things we need to look at one is in the package json if you haven't already installed axios for this project now is the time to do it you can see i've also got some font awesome dependencies in here that we're using in the register form other than that it's just react react dom and react scripts but you'll want to pull up the terminal and get a new terminal if you're running the app here so we'll click the plus get a second terminal and you can do npm i and then axios which would install it now you probably need to restart the app anyway after you do that so with that said you could just do control c here to stop install axios and go back either way you just need axios installed for this project and now that we've looked at that create an api folder i already did this for the registration tutorial inside the api folder that's in the source folder create an axios js and this is what you want in the axios gs import axios from axios and then we want to have a default here export default axios.create and we're setting the base url so we don't have to do that anywhere else and then when you import axios into your other components it will be from this file so let's close out this and go ahead and import axios into our login component so we'll import axios and this will be from dot slash api slash axios there we go and then we also need to define a login url constant here that we'll use with axios and i'm just going to set that equal to slash auth which matches the back end that is created in my node.js for beginners course and we're now ready to complete the handle submit function with the authentication and test it with our back end that was created in the node.js for beginners tutorial and once again if you don't have that it's okay to go ahead and learn from this and then maybe learn how to create that for yourself later so let's remove this log statement for now and we will use pretty much the rest of everything here for we'll again use the set success just for this tutorial everything else will remain and will be used so now we'll have a try catch block and after the try of course we have the catch it receives the error there we go inside the try block we could go ahead and put all of these actually updates to state because we would want to do this if the try was successful but what we need to start with is defining a response and then we're going to set this to a weight notice we had async up here to define our handle submit so this will be await axios.post and inside of this we're going to pass in that login url which will attach itself to the base url that we already defined in the axios file that's inside of the api directory and then the second parameter for axios will be json.stringify and then we'll pass in user and password now this is what the api is expecting the rest api that we're sending this information to if it was expecting user name we would have to change the name and then provide user here so we're really kind of destructuring an object but if we provide the same name for our state as the property should be named then we can just say user and password like this without the actual key or saying password if that's what the api was expecting and then providing the value so here we've just got user and password just like the api expects and then the third parameter that we're passing into axios should be an object and inside of this object we can have headers inside of this header is another object and it has a content type property and this is set to application slash json after that we need to put a comma because we're still inside of an object as well we want to say with credentials we're going to set that to true there we go and we're basically finished right there with axios i'm going to bring this down to one more line and put the semicolon afterwards and save there we've got some better formatting now the great thing about axios is it will throw an error if there's an error we don't have to check here like we do with fetch to see if the response was okay and likewise we also don't have to take the response and convert it to json axios will do that for us immediately too so right now we should have some data if this was successful so if we want to log to the console we could once again say json and here we'll say stringify and we'll pass in the response and i'll go ahead and use optional chain in here but the data we get back should be inside of the data property of the response and likewise you could go ahead and i'm going to do shift alt in the down arrow you could just stringify the whole response if you want to see everything in the console it could be a little large though so i'm going to comment that out but i'll leave it here in the source code for you i'm going to scroll up just a little bit but what i'm interested in getting from the back end that i know will get is the access token we want to store it with the other user information so that comes from response and then optional chaining again data and then i'm going to say optional chaining again and say access token if it's there and then we'll also get the roles now this isn't something that i sent with the data in that node.js for beginners tutorial but we did define the roles so if you have that source code and have completed the course just grab the roles there and go ahead and send them in the response as well so we'll set the roles equal to response and then data optional chaining again and roles the roles should be an array of roles that we're sending back and they're actually numbers that are assigned the different roles on the back end but that's just a convention in any given employer or api could be different so that's just how i did it for the tutorial those codes or roles essentially are made up but now that we've got this extra information we want to go ahead and call set auth and it is an object and here we're going to pass in the user the password let's not do the access token first let's do roles first and then the access token so we're going to store all of this information inside of our auth object and that's saved in the global context so that's if everything goes well but what about if we get errors we need to handle the errors we might receive as well so let's put in some conditional logic i'm going to use if statements here you could use whatever conditional you want and i'm going to look for the response first from the error and basically if there is no response at all but we've got an error then we're going to set the error message and i'm going to say no server response but then we can have an else if and we can start to look at some codes here so now we know we've got a response if we've made it this far but then i'll put optional chaining for the status and we'll say if that equals 400 we'll give a specific reply and so then we'll set the error message equal to missing username or password essentially a 400 means the information that was expected was not received then we'll put another else if and here we'll once again do error response and then we can chain the status and look at a 401 which should mean unauthorized so we'll set the error message to unauthorized and then we should have at least an else here afterwards and then we'll set the error message simply to login failed but of course you could put in other error codes other messages just depending on what api you're working with and what you expect to get back but we're not quite finished because after we get an error no matter what that error is we need to set the focus on that error display so a screen reader can read that information that's where we had that aria live attribute and we set it to assertive so it is announced immediately okay we're ready to test our project now with our node.js backend however a couple of notes on that first so if you have completed my nodejs for beginners tutorials i'll pull this over i want to highlight a couple of things one in the config directory you should go to the allowed origins and we're running our react app from localhost 3000 so you want to make sure that is in the allowed origins or cores will block the request altogether and you will never get a authenticated response the next is the auth controller here so i did bring up sending the roles and here's the response json in the auth controller i'm sending the roles and the access token one other thing to highlight here i'll press alt z to get the code to wrap is where we define the roles in this auth controller i noticed i was getting some null values back as well and that i think is just coming from grabbing those roles that we had before we had three so maybe a user had two and you would get one null so you can just add a dot filter and pass in boolean it's a neat trick to just eliminate all of those nulls then you'll only get those values just a couple of quick changes i wanted to put there before we go ahead open up a terminal here this is another instance of visual studio code for those of you that had vs code open for react i've got a second version open here now for this node back end i'm going to type npm run dev and launch the back end as well which should start running on port 3500 here very soon and we should see that in the terminal there we go connected to running on 3500 i'll drag this back off screen but keep it running and now we're good to go as far as testing our codes so let's resize and i'll go ahead and hide the file tree too so we can see more of the code over here but let's test all of this out i'm going to put in my name and now we're testing an actual password a password that i know exists so we have to meet all the criteria there and go ahead and enter and yes i'm logged in and it says go to home so let's expand this and look at the console and see what we got as a response here was our response notice we got roles and then i've got two role codes here 2001 and 1984 and then we got an access token back as well now i could have console logged the username and the password that i typed in as well and all of that gets stored in the global context with the use context hook so everything's working as expected and i could reload this and i could do another name that i have in here for a test let's put in jane and now let's try her password if i remember it there we go and i'm logged in just fine as well so that also works that's all good so now let's try something that doesn't exist i'll do james123 and that is unauthorized so that user code is also working as expected let's go back to our code real quick i'll close that out get this over here to the right and if we look at our login right now we set this up so the input for user and password are required but let's just temporarily remove the required for the password so we can get a 400 back and i'll send an empty password value and yep missing username or password so that also works go ahead and control z to change that back and now i'm just going to stop the node server so we should not get a response at all so let's test that out and it'll need to timeout so it'll take just a second but then we should get our other error response that we expect yep no server response okay so everything's working as we expect it to we've created a register form in one tutorial and now in this tutorial we've created a sign in or a login form but what we need to do is pull it all together and that's going to be in the next tutorial remember to keep striving for progress over perfection and a little progress every day will go a very long way please give this video a like if it's helped you and thank you for watching and subscribing you're helping my channel grow have a great day and let's write more code together very soon
Info
Channel: Dave Gray
Views: 493,370
Rating: undefined out of 5
Keywords: react user login and authentication with axios, react user login, react js user login, authentication, axios, reactjs user login, react login, react js login, reactjs login, react login form, login form, react js login form, reactjs login form, react user auth, user auth, react js user auth, user authentication, react user authentication, react axios, axios login form, axios auth, axios form, react, react js, reactjs, react tutorial, Js, Axios react, react axios form, auth
Id: X3qyxo_UTR4
Channel Id: undefined
Length: 31min 36sec (1896 seconds)
Published: Fri Jan 07 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.