React Forms with Redux & RTK Query | MERN Stack Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
react forms with redux and rtk query will help us complete crud operations in our mernstack project [Music] hello and welcome i'm dave today we will integrate react forms with redux and rtk query in our mirnstack project i'll provide links to example source code and all resources in the description below in the previous lesson we set up redux and rtk query to store and query data for users and notes today we'll set up the remaining crud operations endpoints in rtk query as well as the react form components needed to create and edit both user and note data and all of that data is kept in our redux store a quick reminder that this mirn stack tutorial series is not for absolute beginners i suggest you start with lesson one in the series and note the prerequisite courses i recommend for success with this mernstat course before today's lesson i highly recommend completing my redux course our starter code is the completed code from lesson six there are no new dependencies today but we've got a lot to cover and i'll need to keep things moving feel free to pause the video as we go and remember all of the source code will be available under lesson seven in the course resources here we're starting in the package json and the only thing we need to do here is increment this to lesson seven today no new dependencies to add from there let's move on to the user stories while we've made progress on many of the user stories we list here and really this is that informal list we talked about in previous lessons we've only completed a couple that we can really say that are completed one of those is to add a public facing page with the basic contact info we did that in the last tutorial and then we also had provide a welcome page after login and i said in the last tutorial actually we did this two tutorials ago as we created the react app and just provided those basic things and some routing to those but today i think we'll complete a few more let's look at number 10 here notes are assigned to specific employees we'll be able to create notes and create that assignment today number 11 notes have a ticket number title note body created and updated dates now we previously set that up on the back end with our data models but now we'll complete that for the front end as well as well as number 12 notes are either open or completed so when we create a note we'll assign that and number 13 users can be employees managers or admins so when we are able to create users with a form we'll also be able to complete that so number 10 through 13 should be completed today some of these others we are very close to completing but maybe we can't say it's completed yet because it also deals with roles and protections and things we haven't applied through authentication and authorization yet or there are things just like provide easy navigation which we have done somewhat with our users list and notes list but we're not finished yet we need to provide some more navigation throughout the application so now with these two boxes checked and our target set on lines 10 through 13 here or i should say goals or stories 10 through 13 let's go ahead and save our user stories.md file and let's move back into the application so we're inside of the source directory and then inside of that we want to open up the features directory and let's go to the users directory and the users api slice we have already added our endpoint for getting the users but that's the only one we added so far so let's go ahead and add the create update and delete endpoints as well so let's find where we started this we have get users this is all inside of the endpoints definition of the slice that we have created here this is the user's api slice that's injecting endpoints into the main api slice for redux and rtk query so underneath this get users endpoint that we defined we can put in the other end points and i need some room to do this and i just put in all three they're not nearly as big as the get users so we'll just go over these the first one is add a new user now notice this is a builder dot mutation previously we had builder dot query but now this is a builder dot mutation and that's what these other methods will be so we're passing in some initial user data and we're going to the user's endpoint we're using the post method and then we're just passing in that data in the body after that we're saying we're invalidating tags now so this will force the cache that we're using with rtk query and redux to update and what we're doing is saying the user list will be invalidated so that will need to be updated after that let's look at the update user endpoint here so another builder dot mutation we're passing in that user data again so it looks very much like the post as far as this endpoint is concerned we're using the patch method and here's the user data inside of the body we're invalidating tags here but now it's not the list now we can specify the id of the user that we're passing in and we get that with the arg parameter that we have right here inside of this anonymous function for invalidates tags so we specify that right there and it invalidates that one user id so we know that needs updated again and remember we specified the ids as well as the list here inside of the provides tags for our get users query so we had the list and then we also mapped over the ids so we can invalidate those as well after that we have the delete user again very similar all that needs to be passed in is the id here so instead of spreading in full initial user data we're just spreading in the id actually we're destruction we're not even spreading and then we have the user's endpoint the delete method and all the body needs is that id and then once again we're invalidating the specific id of the user and now as we scroll down remember rtk query automatically creates hooks for us so we had our get users in point and it created use get users query that was a query now remember these others are mutations so as i put these in here you'll see now we have use add new user mutation so it's named after what we created as far as an endpoint which was add new user and then they always append use at the beginning for the hook and mutation at the end just like query was appended at the end of our get users query so we have use add new user mutation use update user mutation and use delete user mutation and we'll be able to use all of those today as we create our forms and now that you understand the additional endpoints we added to our users api slice let's do the same thing very quickly for our notes api slice so once again we're inside of the endpoints builder and then we have the get notes builder query so we'll come down right underneath it and we'll paste in the other three which you could create as well or grab from my source code but we've got add new note update note and then finally delete note and this has the similar logic that we just went over for the users endpoints as well so nothing new there now let's come down to the export and we're going to export these three new mutations that we have here as well now before we create our forms let's go ahead and add some placeholder components i'll go back to the users directory and create a new file and this first file will just be named edit user dot js and i'll use my es7 react snippets extension to quickly create a component and this is just a placeholder component so i will save the file and now i'm going to create another new file and this is going to be called new user form dot js and once again i'll use rafce to create a new user form just a placeholder component for now so we have edit user and new user form files as placeholders now let's do the same thing in the notes directory and i'm going to create edit note if i could spell edit correctly.js and rafce with es7 react snippets and i quickly get that functional component placeholder and then i want one more and this is going to be new note.js notice i did not name that new note form it's just newnote.js and there's a reason for this i'll do r-a-f-c-e we'll come back to that reason soon but let's save that and now we have four placeholders for our form data so we have two for notes and two for users i wanted to do this so we could go ahead and add the routing inside of our app.js file now to do that we first need to import these new components so at the top i'm going to import first edit user and after we get that i'm going to import new user form and then after that well i don't i'm not quite at the end there we go i'm just getting rid of that semicolon that i'm trying not to use as often anymore then i'm going to import edit note and then finally we need to add import [Music] new note and remember it is not new note form it is just new note for now okay with those four imports we can now add our routing below we've already created our notes route and our users route and at this point i think i want to put notes below the users route so i'm just going to switch those around it won't make any difference which is above the other here so we have the distinct routes of both users and notes just because i'm going to do users first here so let's go ahead and add a route and now inside of this route we need to have a path this path is going to be equal to the id parameter so we're sending the id parameter and that will be part of the path so we'll go to the dash we'll be at the root of the website or web app and then we'll have slash dash slash users and finally the user id all inside of the url now besides that we need to specify the element so we'll say element equals and inside of this we will put edit user and then we'll have our edit user component and instead of this closing route i think we can just close it out inside of the same so we have the slash greater than instead of the closing route symbol there at the end or the closing route tag and once we've done this let's copy this down and we'll have one more path inside of our users path and this will just be to new so we could have slash dash slash users slash new and this should be the new user form and now i'm going to copy both of these and put them underneath our notes list as well because it will have the same path pattern for notes so it will either go to the id parameter in the url or new so we just need to change what we have here as far as the components so we'll have edit note or we will have new note once again it is not new note form before we begin building our forms there's one more thing we need to do i'm going to go ahead and collapse the features directory we need to be just inside of this top source directory and create a new directory named config now inside of the config directory i'm going to create one file named roles.js and i will paste this in it's very simple we are exporting an object named roles and this would be a lookup object and notice the key and actually the string value are the same so roles dot employee equals employee we're going to use this in more than one file so i wanted to just create this object one time and put it inside of a roles js that we can export and then we can use it in the other files we need let's go back to the features directory and back inside of the notes directory and we're ready to go ahead and update this new user form component i'm going to start at the top with the imports again i'm going to move faster and paste things today and then go over what i am pasting in and of course feel free to pause slow down or look at the source code that i'm supplying for this lesson but we're importing use state and use effect for this new user form we're also bringing in the use add new user mutation that we created inside of the user slice i'm bringing in use navigate from react router and i've also got a font awesome icon because we're going to use a save icon from that and then the roles that we just created are going to be used in this form as well being a new user form that means we're going to have some new input for the user so i've got a couple of regex constants that i am creating as well again this won't be a public facing form this will be something dandy or his manager will use to create for new staff members to create a new user so we just need to put some guidance here as far as what can be entered for a user or a password but we're not being as strict as we might be for a public facing new user creation okay once we have those regexes we're ready to start working with our use add new user mutation inside of the component so now inside of this new user form component i'll paste that in and we'll take a quick look at what it does and what it brings into the component so this unlike the query gives us an add new user function that we can now call when we need it inside of the component so it is not activated immediately and then there is an object that of course delivers the status after we call this function so we have is loading is success is error and error much like a query but the query was called immediately when we used that inside of our list components this is not called until we're ready to call it underneath this hook let's go ahead and paste in the other hook that we get from react router which is just pulling the navigate function that we will also call whenever we're ready to call it from use navigate and now we've got some individual pieces of state that i'm using use state for we've got the username but then we're also going to have a valid username that is only going to be true of course when it meets our regex standards same for password and valid password and then we've got the roles and set roles so we can set those and we're defaulting to employee right away for that value but notice it is an array so there could be more than one role assigned to an employee or a staff member and we did bring in use effect and that's going to help us validate our username and password so we're just going to check both of those so we have username and password as dependencies in each one of these and as they're changed we're just testing those reg x's that we defined and in one more use of use effect we're going to go ahead and check that is success status that we get after we call our mutation so if it is successful we're going to empty out all of that individual state that we're keeping here really and we're going to navigate back to our users list that has that is at the dash slash users url now is success does change and when it does change that's what will trigger this you will get a warning or a complaint if you do not include navigate in here although we know bringing in the navigate function from react router will not change so i just put the navigate in here as a dependency to remove that warning now let's go ahead and scroll up to have some more room and i'll put in the handlers that we're going to use instead of starting them with handle i started them with on and then we have on username changed which just sets the username on password change which sets the password but the roles are a little different and that's because it's a select and then we're doing something specific with them so let's break this down we have on roles change that also receives the event but then the values we get we need to build an array from those values because when it comes in with the event.target.selectedoptions it is an html collection and that won't give us the same thing we need so we're using array from and then array from not only takes that value but it also has a function and then we can just get the option dot value from that and create an array stored in values and that's what we need so then we set the roles to those values after that let's go ahead and put in our save and we define a can save before we actually allow the onsave users clicked to really kick in and do what we need it to because here we check if can save so let's look at this can save i'm going to press ctrl b to hide the file tree just so we can see that full line here but we've got can save defined and notice we've created an array and inside that array we put the roles.length because that's an array we've got valid username and valid password then we're calling the every method on the array and passing in boolean so we're essentially saying if all of these are true you could say if roles dot length and valid username and valid password but i kind of like this method for doing it sticking them all in an array and then having dot every with boolean and then we do have the ampersand and we're also checking the is loading status so we're saying and if we're not loading then can save will be true and then we check that can save value inside of our onsave user clicked and this is where we call our add new user mutation and once we call that we're passing in the username password and the roles now before we create our jsx for the form we've got just a few more things to define so i'll put those in here and we'll quickly look we are going to have a select so it needs options now previously we discussed how to get the value out of that and that's what we had up here inside of our on rolls changed well what we're looking at here is object.values and then we pass in that roles object that we defined inside of our config directory and import it so now when we pass that in we're just getting the values which was employee and manager and admin and for each one of those we're creating an option that can be inside of that drop down menu that we should have and we're actually going to display all of those so we should be able to select more than one and we'll get to that in a second but first we have some other things we're defining here and these are classes that we may or may not want to apply to some elements in the form one of those is an error class so we're just checking to see if we have error and which class will be applied here either error message or off screen another is the valid user class the same for valid password class and valid roles class so we're just checking to see if those are valid and if they are then we're not really applying anything but if they aren't we're giving the form input incomplete class which will just outline those in red and highlight the fact that something needs to be completed with those inputs i'm going to replace our return right here and just return content so now i want to define the content variable it's going to take up some space and we're actually going to need to scroll through that so i'll put it right here and give one extra line before the return and now let's look at each part of this form that is held inside of the content variable notice i have got a fragment here as the parent for valid jsx and the first thing we're putting in is a paragraph with the error class and that error class is defined above so it's either off screen or if we have an error it's going to display that error message at the top of the form and remember we gave some detailed error messages from our back end that it can provide to the front end so these will be displayed at the top of the form if any of those errors do occur then we have our form so here is a class name form remember the class names that you see here are going to relate back to the css that i've created you can use my css or you can create your own as well so my class names are relating back to my css here on submit for the form calls the onsave user clicked so that should work for the entire form and then we have the top the title which is new user and then we have a button and this is where we're using that font awesome icon with the save icon and notice this button has a class name a title and then we set the disabled and so if can save is false we're using the exclamation mark here to flip that value disabled would be true so if we are not meeting the requirements for saving the new user then this button will be disabled so we're getting double use out of that can save variable after that we have a label and you should have a label for each input and what we're doing here is providing the username and some details here we're saying it must be three to twenty letters and then inside of this we have a class name and here's that valid user class value that might be applied if there is an issue with the username or if it's just blank it's highlighting that it needs to be filled out we've got your basic attributes here including autocomplete set to off because we don't want other previous names popping up and this is a controlled input so we have the username state here and we're calling on username changed during the onchange if that happens very similar for password we give some details here 4 to 12 characters including these characters right here and after that it's a controlled input and the same for the valid password class now we get to the roles what i want to highlight here with the roles is that multiple is set to true so you can select more than one value and the size is set to three so it will display three values without being a drop down all three values will be visible and then it is a controlled input so we have roles and on roles changed and then we're bringing in those options that we defined above and with that we have completed our new user form let's go back to the file tree now and highlight that edit user component let's go to the top of the file and we'll bring in our imports first and not nearly as many for this particular component we'll have used params from react router because we're going to get that user id parameter out of the url and then we're going to bring in use selector from react redux and select user by id so notice we are not bringing in a query we're actually going to pull the data the user data from the state and we're going to get that by selecting the user id so now i'm just going to highlight the return and i'm going to replace the content of this particular component and there's not a lot because we're going to use another form that we haven't created yet and that is the edit user form so what we've got here i'll go ahead and save is pulling that id from the use params from react router that will give us the id value that is inside of the url and then we're passing that id value in where we're using the use selector hook and select user by id remember that is a memoized query there that we created ins or a memoize selector that we created inside of our users api slice so we pass in that id and we get the user in return that has that id now what we're checking here for content is do we have a user if we do we're going to pull in the edit user form that we haven't created yet but if not we're just going to provide loading if you had a loading spinner that you wanted to use here instead that's fine this is just a small paragraph that says loading and then we're returning that content so this is ensuring we have the user data before we need it inside of the edit user form and the reason that is helpful is because we want to pre-populate that form we need the existing data to show up in the form and this will confirm we have it as we render that edit user form so now let's create the component we need so we'll come over here and create a new component and call it edit user form dot js as you might expect this will be very much like the new user forum we're essentially editing that same information so i'm going to go fast but highlight the changes we're pulling in basically the same things with a few changes here for the imports we've got use state and use effect again but now we're pulling in the use update user mutation and the use delete user mutation instead of the add new user mutation and then we've got use navigate again we've got font awesome but then we're pulling in not only the save icon but also the trash can icon if we want to delete then we're once again pulling in the roles from our config directory after that we're going to have this same regex at the top because we're going to need to check those same fields for the same things once again underneath this i'm just going to type rafce to go ahead and get a start on this edit user form component and we're going to destructure the user as we bring that user in as we were doing that inside of edit user we see here the edit user form and we're passing in the user as a prop i almost well i need to control z to undo that i didn't mean to drag that over but the user gets passed in as a prop for the edit user form okay back in the edit user form we're using the two hooks now use update user mutation and use delete user mutation they might be called at different times but we need some different identification for each so as i paste these hooks in i want to highlight that the first one update user just has is loading is success is error and error that we might expect here and i can put this on a separate line but after that the second one use delete user mutation notice i am renaming the is success to is dell success and the same for is error and the error itself as we might need all of those now we've got our separate functions that we can call to delete user and update user and now i'm going to scroll up for more room and underneath those i'll paste in the navigate that we're pulling from use navigate as we did with the new user form and then we've got some state and it's essentially the same state that we had in the new user form with one addition and that is active and set active this has a default value of active inside of our data model when we create a new user but now we want to be able to change that to quickly disable an employee as our stakeholder dandy has requested so if he were to let somebody go he might want to remove their access immediately they may still be assigned to notes and he may not want to have to make all those changes before he deactivates a user so this is the state here that will help us do that inside of the form and then we will have the same use effect underneath that checks for the valid username and valid password oh i had it before already too i had grabbed it before so i'll just remove that once again sometimes i get a little ahead of myself when i'm copying and pasting after that we've got use effect now this use effect checks the is success status but remember we have two mutations now so we have to consider both of those and so we're still just using one use effect and it's checking the is success status or is delete success remember the is success is for the update once again passing in that navigate function to avoid any complaints inside of our console about that but we're checking here is success for the update or is delete success for the delete and now as i look at each one of these they're essentially doing the same thing and sometimes we can get caught up in that when we're writing code we write one and then we look at the other so just a quick refactor here we could say if is success or if is delete success and then we should be able to remove one of these blocks because the rest of it the consequences of those being successful it they're both identical so we remove that and now this is a little smaller but it does the same thing i'm going to scroll for a little more room and underneath this we will put in our handlers and they are very much like what we saw in the new user form as well so we've got on username changed and on password changed no difference there on roles changed where we're doing the same thing with the roles as before with array.from but then we do have onactivechanged which is new but it just sets the previous active status to the opposite because it's a checkbox so it's either active true or false essentially and then we've got on save user clicked here we have to check to see if we have a password because we do not want to require the password to be updated every time we edit the user so it's just optional and that means we must call update user two different ways one with and one without the password then we also have on delete user click that calls that delete user mutation and just passes in the id scrolling up a little bit now just underneath that delete user let's go ahead and put in some more where we define can save this can save variable is once again needing to check to see if we have a password and if we do can save is going to be using that valid password inside of the array that calls.every with the boolean notice over here there is the is loading status as well i'm going to press control b just so we can see everything on the screen and then can save has the array without the valid password in it if password is not being created as well so we're checking either way there and then we have the same classes that we did before as far as error class valid user class valid password class valid roles class then we're creating some error content and notice there is a difference here it's whether we have an error dot data dot message or a delete error so this is based on the update or this is based on the delete mutation and then instead of a ternary this is a null collecting operator so if the error or delete error are essentially undefined or null then we'll just have this empty string here that would be in the class and it won't change the presentation where i said class this is actually the error content itself so the content would be empty if that was null or undefined and now speaking of content that's what we need to return next so i'll just modify this return right here and change it to content and let's define our jsx with the content variable and this of course takes up more room than the screen has so i'll scroll back up this is very similar to our new user form except in the edit user we've got a couple of additions so here's that error content with the error class provided if it exists otherwise that off screen class hides it off the screen and then we've got our form this form not only has our save button as the previous new user form did it also has our delete button and this is where we use that trash can icon and this will call cause that delete user mutation to be called just like the save user here will cause the update mutation to be called then inside of the form we've got the same inputs except for the addition of this active check box so here's the check box it is still controlled with checked either active or of course not whatever is there and then we've got the on active changed handler being called other than that we still have the assigned roles it is still set to multiple true so we could assign more than one role we're displaying all three roles at the same time so it's not a drop down as much as it is a list where more than one can be selected with those changes in place i'm going to save the file and now i want to bring over another instance of visual studio code that has our back end code in it so i'll bring this over to the screen this is from lesson four the last time we touched the back end code i'm going to press control in the backtick and go ahead and start our back-end development server here this is the rest api that's a big part of our mirn stack application it's now connected to mongodb it's running on port 3500 remember this is the code we finished up in lesson four and i've opened a separate instance of visual studio code to run that so now if i want to i'm just going to minimize that and look at our existing code here i'll go ahead and press ctrl and the back tick and i'll type npm start for our react app and we'll see if we can view the forms we just created or if we have any errors now i'm going to drag this over to the left and we've got our application running here on the right we should be able to go to the dash that we've previously created and now we should be able to go to the users list so let's check that out and we've got employees in here that i previously created that you should have seen in the last tutorial we've got dan d the stakeholder he's the owner so he's an admin as well as a manager and an employee so you can see different roles are applied to the same user we've got mark who's an employee and a manager and then we've got joe who has the role of employee now i'm going to drag this over to the left because there's some things we need to highlight as far as using redux before we get into each individual form and how we maintain that state so i'm going to press ctrl shift i to open up dev tools notice i really shrank the application because i want to use redux dev tools if you don't have those of course you want to install those and i can put a link to those in the course resources as well but here i'm highlighting the state in redux dev tools and i can open up this api and notice there's a subscriptions right here and if i open this up we've got get users that we needed our get users query to populate this users list and inside of get users we have a subscription set right here and it gets this long string now let me go ahead and go to dandy's page and here we've got the edit user screen that we created notice there is no subscription and now it went back to loading after just five seconds why is all of that happening well let's take a look at why that is happening so to do that i'm going to close this out drag our application back to the right and drag visual studio code back to full screen close the terminal and let's look at our users api slice once again and if you remember i set the keep unused data for to five seconds and i wanted to highlight this in development because after five seconds we went back to that loading screen it only kept that data for five seconds and that's because there was no active subscription to the data so after the all of the subscriptions are gone that's when this countdown kicks in now the default value is 60 seconds so if there still wasn't a subscription to our users list after 60 seconds we would use the state of our editor's form and it would go back or our edit user form and it would go back to loading we don't want that either so there's a couple of solutions here first of all i'm going to just remove this as we no longer want it inside of here and the default keep unused data for 60 seconds will be fine but we'll see how we can keep an active subscription and that won't be an issue either so while i'm thinking of it let's go to the notes api slice as well so we don't have that same issue because i believe i kept that in there too so also remove this keep unused data for five seconds and just leave it out of the slice altogether now what we need to do is create an active subscription that remains active even though our user our edit user form i believe we're here in edit users where we got the data it is just using the use selector so it's not querying that data again and that's why we don't have a subscription but we've already queried the data we don't want to send another query when we already have it so we're not using rtk query although rtk query would know we already had that data and create that subscription we're using a use selector so somewhat of a preference but also just to demonstrate what is going on here so we're pulling this out of the cache and out of the redux state and using select user by id rather than creating a new subscription and we want the notes and users throughout the application so it's really no problem to create a subscription that lasts for the duration of our protected pages so to do that let's close out the users directory let's close out the notes directory let's go to the auth directory and let's create a new component in here and we're going to call this pre-fetch.js now rtk query and redux toolkit does have a use prefetch hook but that's not what we're going to use let me start out with a few imports here inside of this file we will import the store from our app directory and the store this is the redux store we're going to import the notes api slice the user's api slice we're going to use a use effect hook and we're going to import outlet from react router dom and now let's go ahead and use rafce to get that functional component started with our es7 react snippets and inside of this prefetch component i'll just paste in the details and we will go over that i'll highlight the existing return and put in our details here i'm going to press ctrl b so this doesn't go off the screen so let's look at this and we can see how it works as well here's our use effect and it's an empty dependency array so we only want this to run when this component mounts when it mounts we're going to log subscribing and i really want to highlight that or leave it in the code for you because of react 18 and we're using strict mode so it's going to mount unmount and remount and we'll see that with a subscribing unsubscribing and then once again subscribing and that's only in that strict mode when you're in development mode but we're going to create a manual subscription to notes and another manual subscription to users that will remain active so that way we have access to that state and it will not expire in 5 seconds or in 60 seconds which is the default and then we'll unsubscribe if we ever leave the protected pages we're going to do that of course this returns an outlet so all of the children we're going to wrap our protected pages in this pre-fetch component this will also help us when we refresh the page and we still want to have that state including pre-filling our forms so now that we've created this prefetch component let's go to the file tree and let's go to the app.js and inside the app.js i want to import prefetch and there we've got it from features auth prefetch and once it's imported all we really need to do is wrap it around everything that starts with our dash which are the protected pages so here we'll have route and then we'll have an element we do not need a path for this and inside of that we will put our pre-fetch component and once we have that we can go ahead and close this because we will want a closing route and we do not want this to close out until after the end of the dash and once we've done that we have now pre-fetched that data for notes and users for this whole area of our application now let's once again go back and look at that prefetch because i was thinking the one thing i didn't explain really is what this is this is the manual subscription right here so we use the slice then we call the endpoints then we call the actual query that we want and then the initiate method creates that manual subscription notice in the cleanup method we are unsubscribing so if we ever go to any of the unprotected pages it will unsubscribe as well okay with that saved now let's see we're still running our application let's drag this back over to the left and now we've got dandy's information on our edit user form and it's not going away let's see if we can change dandy's name to a lowercase d at the end just for an example we'll click our save icon now we're back at the users list and we have added that addition to dandy's username let's go ahead and change that back and now we can also see in the roles we can hold down the control button and just select one or none but then it's outlined in red saying hey we need something here notice also when this is outlined in red the save button went away so our can save variable is working as expected too active or not active and of course dan needs all of these roles and we're not changing his password right now so we'll just leave this empty but that's okay because we do not have to have it although we did it looks like we applied the red around this even though we're not actually requiring the password when we edit the user so we may want to change that also while we're here let's go ahead and go back to the edit and notice if i refresh the page we reload all of that data because we're already subscribed and that hits the prefetch component first before it comes here so that really helps our consistency if someone hits the refresh or reloads the application in any way now what else do we need to check well let's go back to our tech notes and we could view the user notes again but after the users we also created that new user form so let's put slash new to check that out and let's create a new user i'm just going to call this new user test and our password is test123 and we'll make him an employee or her and a manager and then let's hit save and now in our list now we don't need that or any help from chrome but and now in our list we have test with an employee manager role and here is that user let's go back and let's delete that user and now that user is gone now what might happen with our list of data here or with our notes data is say this was open on more than one employees screen or more than one staff member and we might get some stale data after it's open for a while so we also want this to refresh the data sporadically or at some type of interval that we can control and we can do that with rtk query and redux as well so now let's go ahead and apply that i'm going to pull this back over to full screen we'll close the terminal for now let's open up the file tree and go to the app directory and our store.js inside of our store we need to import setup listeners and notice this comes from redux js toolkit query and i'm going to get rid of those semicolons just because i'm trying to be consistent now after we bring in setup listeners we just need to add it at the end of our file and we call setup listeners and pass in the store.dispatch once we've done that we've enabled some things that we can use now with our queries in the users list and in the notes list let's go back to the users directory we have inside of the features directory and back to our users list notice we're just calling use get users query here inside of this component but we can pass some things in including options so i'm going to paste this in we just put null or you could put undefined here as well this would also work if we did that after that we have options and what we're using here for options are a polling interval refetch on focus and refetch on mount or arc change really if we remount the component we're going to refetch the data that's set to true if we put the focus on another window and come back to our browser window then we'll also refetch that data so we'll be looking at fresh data and then we're setting the polling interval to 60 seconds this is 60 000 milliseconds essentially so every minute it will re-query that data and if we have the page open to a users list then we will get new data again and we can also do this inside of our notes list so let's go to the notes directory and inside of the notes list we'll do something similar but i would expect the notes list to be more active i'll once again change this to undefined it should work either way but i believe the documentation shows undefined when you do that afterwards we're just going to change that polling interval to every 15 seconds because the notes could be more active more than one person could be working on them so we'll show the most recent data in the list at least every 15 seconds after that refetch on focus and refetch on mount or arc change will both be true as well so after setting this polling interval you should see a new request for notes every 15 seconds inside of your network tab of devtools of course you could adjust that if you didn't think it was necessary that frequently or you needed it more frequently either way but those are nice features to add when you have more than one person working with a list of data and they're needing to reference that data for any changes and now let's go to the welcome component that's inside of our auth directory and we have links to the lists for tech notes and for the users list but let's go ahead and highlight those and i'll just put in two more links with it so we goes directly to the add a new tech note or add a new user link as well now that said we haven't created the forms yet for the notes so let's get started on that is we have a new note and an edit note component now just like our edit user component that had an edit user form component that was pulled in our new note component will have that and you would think okay but why didn't the new user have that well the new user has all new data but the new note actually needs some existing data so we're going to pull in this use selector and select all users and then there needs to be a new note form component that we will also use inside the body of the functional component i'll just replace this return and we're going to use that selector with select all users which is a memoized selector that was created inside of the user's api slice and get all of the users once we have that we're going to check what kind of content we want to render if we have the users then we're ready to render the new note note form that will be populated with users data to choose from as well so we can assign that note to a user if not we'll just have a loading message and then we return that content so let's go ahead and save that file and let's go into our directory and create that new note form dot js component we could r-a-f-c-e for a placeholder and just get that new note form component there so we don't currently have an error we should go back to the new note and import that and we did so that's good we already have that so no error there when we try to check it out now we're at the edit note the edit note has a little bit more to import at the beginning so let's go to the top here and go over the imports oh i got rid of the name there there we go return that now go down and paste in those imports now we're bringing in used params because we're going to need the id of the note we've got use selector select note by id which is that memoized selector that's now created in the notes api slice since we're dealing with notes we also need the users though so we're going to select all users here as well because this form will be very similar to creating a new note and then we're bringing in the edit note form that will also need to be created so we're bringing in data once again and then rendering a pre-populated form to edit that information so let's go ahead and replace the functional component information here we're going to get the id from use params which should look very familiar to you after we did the same for the users now we're getting the note data for the specific note that has that id with a selector we're also getting all of the users that we need again now our content is going to check to make sure we have the note data and the user's data and if we do it's going to render the edit note form and after that of course we're passing in the note and the users both as props there if not we have the loading message and after that we return the content so now let's go ahead and create an edit note form placeholder as well so edit note form dot js for the component rafce to quickly create a functional component and we have placeholders for edit note form and new note form now this is very similar to what we have already done with the users where we had the edit user form and you can use that pattern what i'm going to do now is give you a viewer challenge much like i did with the controllers we've already spent a lot of time going over these patterns so now apply what you have learned and try to create your own forms here needed for these two placeholders and of course i'm going to put my code in the source code for the lesson so you can go back and check as well but i think this is a nice place to stop and give you that challenge and we've got everything else in place 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: 15,846
Rating: undefined out of 5
Keywords: react forms with redux, react redux form, react form, redux form, react redux forms, mern stack, mern stack tutorial, react, redux, react redux, forms in react, forms in redux, rtk query, rtk query forms, populate forms, populate forms with redux, rtk query subscriptions, redux subscriptions, redux and rtk query, rtk query with redux, react with redux, forms with redux, forms with rtk query, prefetch, redux prefetch, prefetch component, CRUD, redux crud, crud redux, React.js
Id: H3Vo2NJgPvQ
Channel Id: undefined
Length: 53min 1sec (3181 seconds)
Published: Fri Aug 19 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.