Learn The Mern Stack [10] - React & Redux Auth State

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
alright guys so in the last video we created the JWT functionality for our back-end with node and Express and Jason web tokens so now we want to jump in to react and and implement that into our front-end so I'm gonna go ahead and run NPM run dev which will run our back-end in front-end and if you remember we added the auth middleware to the routes that added an item and deleted an item so notice if I click delete it's not going to work if I look in the console here it's a 401 error which is what we sent back because it's unaware unauthorized same thing if we try to add an item that's not going to work either because we have to send that token along so we need a way to log in so we've quite a bit of work to do in terms of just handling our state with authentication as well as the actual components to login what I would like to do is have a modal like this to login and register ok so I think before we create the components though we should deal with the state so we want to work inside clients and we're gonna have two new reducers one is going to be an author ado sir one's gonna be an error reducer and we'll also have an often errors actions file so we're gonna need some new types ok to work with so in actions types J s I'm just gonna paste these in just to save some time actually let me grab them first so let's see I'm just gonna grab real quick one second alright so as you can see we have quite a few here all of these have to do with the whole authentication and registration process and loading the user and so on and then these two have to do with the error reducer we just want to be able to get errors put them in our state and clear them if we want so let's save that that's actions types and now let's create our reducers so in the reducers folder here I'm going to create two new files one is gonna be error reducer J s and then let's also create one called off reducer jas okay and then an index j s inside with the reducers folder we need to bring those two in so let's bring in ever reduce our oops and let's bring in author ado sir and we need to add those down here so the error and off okay so let's start off with the ever reducer just because it's it's much simpler we just basically have get errors and clear errors inside of our reducer function so let's import oops let's import from dot dot slash actions slash types and we're gonna want to import get errors and clear errors okay then we want to create our state our initial state which is an object which is going to have a message which is going to be adjacent object and that comes from the server we're going to have the status that comes from the server set that to null and then an ID if we want to grab a certain error and do something with it within a component and you'll see what I mean later a lot of this stuff might not make complete sense to you but I think that later on when you see how we implement it it'll make a lot more sense so keep that in mind so let's explore default function here and our reducer function takes in the state which is going to be set to the initial state and then also an action that's sent from the actions file and then we need to evaluate the action type a switch statement for action type and let's say case get errors then we want to return as far as these the error state we want to return the message which is going to come from the action payload so the payload will be an object that'll have a message attached to it that comes from the server also a status which will come from the payload and also the ID not all errors will have an ID it's just if we want to target a specific error for something that's ID all right so that's get errors now the next case we want is clear errors and in that case we just want to return we just want to basically set everything back to default so message will be an empty object because we don't want the the old errors hanging around in our state so status will be null and ID will be null okay and then just put some semicolons here and then we just want our default state or our default which is going to be just we're just going to return the state as is okay and that's it that's our errors reducer so pretty simple now for the author inducer we're bringing in quite a few things here so I'm just gonna paste this in I'm bringing in everything to do with the authentication as far as the initial state if you watched my reactant Jango series on YouTube this is very very similar in fact I think this might be identical to what we did there so just to let you know that so we're gonna have a token which is gonna come from local storage okay if there is one set so local storage dot get item and we want to get the item of token okay is authenticated it's gonna be set to null by default is loading so if the user is loading that's gonna be set to false and then the user itself will be set to null by default okay so that's our initial state now we have to create our reducer function so let's say export default function takes in state which is equal to the initial state and then action so we need to evaluate the action type and let's first add the case of user loading so user loading is just the point from where we're trying to get the user from the back end to the point to where we actually fetch the user so all I want to do here is return the current state so use the spread operator and then is loading will be just be set to true okay now once the user is loaded you know I'm gonna turn my format on save back on real quick so let's just go to settings and I'm using pretty air and I want my code to format on save so I have to do less work okay so the next case is gonna be user loaded okay so when the user is actually loaded then we want to return the current state and we want a set is authenticated to true okay because we went we went and validated on the back end got the user set that to true is loading should then set be set back to false because the user is now loaded and then user will be set to the action dot payload okay which way we're gonna send the user as the payload so this user loaded is is gonna run basically all the time with every request to see if we're logged in or not okay let's see next case we have or actually going to have a couple cases because on login success and register success we're going to do the same thing so we're just going to do login success as well as case register success and it's hip so I put a comma there so in this case we want to return basically we want to kind of do the same thing we did here I'm just going to copy this return okay so I'm going to do that except we're not just setting the user we're also getting the token which is going to be included in the payload so we're gonna just include the entire payload here so action dot payload and that's going to have the user and the token okay remember that's what we're sending back from the backend and then is authentication our authentic he that is true is loading its false get rid of that comma okay so let's see the next thing is if we fail if thou if the authentication fails also if we log out if the registration fails this is all it's all going to do the same thing it's basically going to turn all this back to null so back to the default it's gonna also clear out the local storage token if there is one so let's actually tab that over so we'll say for the case of off underscore error also case of login fail case of log out success and the case of register fail so for all of these we want to return current state and then token is going to be set to null we're going to clear out the token user is also going to be set to null and is authenticated is obviously going to be set to false and is loading I'll make sure that that's also false all right and then the last thing is just the default so let's go right here and say default and we just want to return state ok so that's it that's our author inducer okay and like I said if this doesn't all make sense to you once we create our actions and stuff like that it should now if we go to our application and open up our Redux tools which you should definitely have installed if you don't just go to the chrome store and install them so in our state let's take a look at what we have here and you can see what actions are fired off items loading and then get items and that's how we're getting our items and in our state we have our current items array okay which which is nothing new we had that before but now we also have off an error so error if we look in here there's there's nothing we haven't done anything with it inside off same thing we just have our default values so token null is authenticated now users everything is no now with every request basically we want to constantly try to load the user so we're gonna have an action called load user so let's head over to let's see close this up close that up and let's go to actions and create two new files one is off actions dot J s and one is going to be error actions dot J s and these are they're going to kind of work together if we get an error it's going to go through the errors action now let's see we have Axios installed we're going to need to make requests obviously so let's import Axios and let's see we're gonna import a bunch of types so I'm just gonna paste this in okay and then the first thing we want to do is check token and load user okay now in order to do this we have to make a request to that API slash auth user and if we look at our back-end let's see if we look at routes auth J yes we want to hit this right here okay so it's gonna look for the user by the ID that's included in the token and then we want it to return the user back to us so we have that means we have to send the token along whoops I put this in errors actions I'm sorry this should actually be in off actions all right now I'm trying to think of how I want to do this let's let's go ahead and just export a function we're going to use an arrow function call load user and we're gonna be using since we're making in the asynchronous request we need to we're gonna need to call dispatch within here so we're gonna go ahead and do arrow dispatch and then another arrow and then our function body okay now I want to I want to be able to get parts of the state I want to be able to get the token from the state so along with dispatch if we pass if we wrap this in parentheses we can also pass in get state and we can get certain parts of our state so in here first thing I want to do is call the user loading or dispatch user loading which basically just changes that value of loading from from false to true so it's a user loading and I'm just going to create kind of a helper function actually no I'm not I'm just gonna dispatch it from here so we'll just say dispatch pass in a type and set that to user underscore loading okay so we want to do that before anything which is gonna call if I go back to my author ado sir is gonna call this right here which is going to set is loading to true okay then we want to actually fetch the user so we're going to use Axios and we're gonna make a get request like I said to slash API slash auth slash user and we have to pass in our token okay so let's go let's actually go above here and let's say get token from local storage so create a variable called token now here's what we're gonna use get States because we want to get dot off so we're using the auth reducer and we want to get the token value okay so what it's going to do is it's going to look at this right here it's gonna look at this right here and this gets the token from the local storage alright so once we do that we need to add it to the headers so headers which in with Axios what we do is set an object and then we add a headers object inside of that okay and then any values we want and of course we need to add content type because we're sending jason so content type application actually we're not sending anything here but I Mac I'm gonna put this into a helper function so I'm just gonna send this content type even if we don't need it let's do the application slash Jason and then we want to check the token so say if token then add two headers okay so if there's a token then we're gonna take that config value and we want to grab the headers and we want to add remember we used X - off - token okay so we want to set that equal to the token from our state that is ultimately in local storage okay and then we want to be able to pass that along here so let's passed along config alright now this is going to give us a promise back so we're gonna say dot then it'll give us a response and what I want to do here is dispatch let's see we're gonna dispatch user loaded so the type remember the type is what we evaluate with the switch statement and we want to pass user loaded and then for the payload I'm gonna send the whole thing so res dot data which should be the user it should be an object with the user object and the token itself alright now if there's an issue so we're gonna go down after the dot then and do a catch so if there's an issue such as that the token is invalid or whatever then I'm going to see we get an error and we're gonna dispatch see you're gonna dispatch an object with the type of off error now this will handle the the functionality it's gonna call off error and then it's just going to set everything to no it'll it'll also remove the token actually hold on one second here yeah I forgot one thing I want to actually remove any token that is in local storage so right before the return let's say local storage dot remove item and let's remove the token okay so just to make sure that if any of this stuff happens everything just everything clears out as far as the auth state goes as far as the user goes all right so that'll happen but also any error we get I want to put I want to run it through our errors reducer so let's head over to our errors actions where is it error actions file and let's import from dot slash types we're going to import get errors and also clear errors all right so let's create a method to return actually I'm gonna put these in all caps so say return errors so export const return errors now I want this to take in a few things a message a status and an optional ID so I'm gonna set that to null by default okay and then we just want to return an object with the type of get errors and the payload which will include everything so the payload will be an object of that stuff so we want message status and ID so that's return errors and well while we're here we might as well create the method to clear errors so it's gonna be very simple we're just gonna export Const clear errors doesn't take any parameters all we want to do is return an object with type clear underscore errors okay so that's it now back in the auth reducer if we get an error I want to actually run this okay because I want to put that error into our state and that's what this is gonna ultimately do is call get errors from the error reducer which is right here it's gonna call this and put everything into the state okay so back in our author deucer I mean I'm sorry our our auth actions down here well first we have to bring it in so up top here let's say let's import from dot slash error actions and what we want to import is return errors right actions return errors yeah so we're bringing that in and then I'm just gonna call it down here in the catch right before we dispatch the auth error okay so in addition in addition to that lets dispatch return errors okay I remember return errors just returns an object like this with the type and stuff like that but it takes in a couple parameters it takes in a message a status and a possible ID so this this right here is gonna give us inside error dot response dot data will give us the message so I'm just going to say error dot response dot data and then for the status we can get that with error dot response dot status and we're not gonna pass in an ID here we don't need it alright so that looks good now I'm gonna save this and we want to ultimately like I said call this all the time so I'm gonna go over to app J s which is basically our entry point and I'm going to bring in that load user action so I'm going to import here load user from dot slash actions slash auth actions and we want to call this when the app renders or mounts so we're going to use component did mount okay so in here what I'm gonna do is say stork and since I have access to the store which is right here we can directly access dispatch and then I can simply dispatch that load user action like that okay so that'll call it directly when the app loads so let's save that see what this says cannot send Hera's headers after they are sent to the clients all right guys so I did some looking into this and the issue is in our middleware in the backend so if we go to middleware off j/s right here where we check to see if the token is not valid which is what is happening in our case we didn't return here we didn't do an if/else so that means that we have to actually return this okay we have to exit from the the function because it's trying to send it twice so let's let's save that and that should fix that error all right so we can close up the middleware and now everything should be okay so if we go back and we check and we just reload and we check out our actions over here what's going on and just make this smaller actually why is this so big let me just zoom oh for some reason oh there we go okay so let's see what happened when the page loads we get items loading which fetches the items user loading okay so in the process like I said between actually making the request and getting the user this fires off however we didn't get user loaded because that only happens if it actually authenticates with the token which we don't have so we get get errors from our errors reducer an auth error from our author ado sir okay but we're still able to get the items because that we don't need a token to get the items now if we look in our state and we look in off everything is still null if we look in error you'll see that we have a status of 401 and the message of no token author ah no token authorization denied okay so this is why I created the error reducer any error like this we get from the server we want to put into our state okay now in the next video we're going to create the login and register components we're actually going to use a modal like this however before I we end the video here I just want to clean up the actions a little bit are this load this load user action because these lines here these three lines are gonna use in any requests that we need to send the token along because we need to check local storage set the headers and then add the token to the headers so I'm gonna grab these these three blocks of code here and cut them and then let's go down to the bottom here let's say setup config slash headers and token okay so we're gonna export Const we'll call this token config and it needs to we need to pass in that get state value as well so pass that in which comes from here because we need that in order to get the token from the state and I'm gonna paste that those three blocks of code in so we get the token set up our config object and then add the token and then the last thing we want to do here is just return the whole config object okay so we want to return config and then up here instead of passing in config we simply need to call token config and just pass in get state like that okay so we now any any time we need to send the token to a certain endpoint we just simply send that okay even if it's in a different file works porting it so we can just bring it in and we can use it alright so like I said in the next video we're gonna go ahead and start on the login and registration and that stuff alright so I'll see you in the next video
Info
Channel: Traversy Media
Views: 69,985
Rating: 4.9219089 out of 5
Keywords: react, mern, mern stack, react redux, react jwt, jwt auth
Id: qyomEaXQJFk
Channel Id: undefined
Length: 29min 0sec (1740 seconds)
Published: Thu Mar 07 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.