React Redux Toolkit Query Tutorial and RTK Query CRUD Example App

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
i'm providing a beginner's example of rtk query we'll build a simple react crud app with rtk query and i think you will see it is very easy to use [Music] hello and welcome i'm dave today i'm providing an introduction to rtk query by building a simple to-do list with create read update and delete requests i'll provide links to example source code and all resources in the description below please note this tutorial is not for absolute beginners in react it is for those that already know react and are beginners with redux and redux toolkit if you are a react beginner you should complete the react js for beginners full course on my channel or one like it at a minimum before attempting this redux series i'm going to move at a slightly faster pace today since i don't expect you to be a react beginner being a beginner with rtk query is totally expected and that's what we're going to work through okay let's look at the package json first and you can see the dependencies i've got here the first three are for font awesome and i'm using font awesome to create some icons that are actually rendered as components and you'll see that in the code if you haven't done that before i'll leave a link to how to do that in the description very easy but you need these three dependencies and so while we're not covering that today that's part of it then of course we've already got redux js slash toolkit that dependency here as well the one to really note today is react has upgraded to version 18 now so that does make a change from what you may be used to seeing in the index file we won't really use any of those features today so much but we're using the new version so before we might have had react dom dot render and notice react dom is now being imported from react dom slash client instead of just react dom if you don't do that you'll get a warning and then we're using create root here and putting the document get element by id right here and then we're just chaining the dot render on after that so some very small changes just due to react version 18 that you see in the index js but not covering react 18 today and really it won't impact anything else we're doing now also in the starter code here that's available for download from the link in the description is a data folder and notice i've got a db.json and it just has all of these to do's in it and that's because we're going to use json server so to install that if you don't already have json server installed now i'm already running the react app here by the way so we're going to just open a second terminal window now to install json server if you don't have it we're going to install it globally type json server and then you would want well actually to install it you'd type npm i json server and then dash g that's the global install now i've already got it installed so i'm not going to press enter right now but that's how you would install it if you need it after that to go ahead and start the server you type json server and then you'll have dash dash watch and then you need to specify where your data is well it's in our data folder and then it's db.json and then we're going to specify a port which is port 3500 and then press enter it will identify our to-do's there and it starts watching that data so now it will support create read update and delete functions okay now that i've got that running and like i said i have the app running over here in the other terminal window i'm just going to close the terminal window for now and close this db.json and let's take a quick look at the app.js and you can see here we're importing a to-do list component that is in a features directory and then a to-do's directory and then there's our to-do list component and this is how you typically organize features when you're using redux so that's the reason for that file structure if you're not familiar with redux okay and then we're just returning that to-do list component here in the app component so really nothing else going on so let's break this out and look at that to-do list component now what we don't have here is any integration with rtk query yet but other than that you may have created a to-do list before if not we'll have the basic code together for one today but we're still going to add some imports here for rtk query we're going to handle a submit and handle adding a new to-do and then as we scroll on down here you can see the form we have and that's for adding that new to do and of course we're using state here so we have new to do and set new to do other than that we're going to create some content based on conditionals conditional content and then we'll render that content here in the jsx so that's all the starter code now let's get started by integrating rtk query into our project we'll start by adding an api directory inside of the features directory so i'll click the new folder up there and we'll name this api which is also the default if we were to name this something else we would have to specify that for rdk query so i'll leave it as the default today which also makes sense it's the representing the api in our code now let's add a file to this api directory it'll be called api slice with camelcase a capital s and then dot js okay inside the api slice this is where we will create our methods to interact with the api it essentially replaces something like axios and pulls that code out of our component logic and over here in a separate api slice which is kind of how we name things in redux if you're familiar with redux and if you've gone through my redux toolkit series okay i'm going to paste in the imports and you can see we've got create api and fetch based query being imported from redux js toolkit query react and so yes this is specific to react you can use redux toolkit and rtk query without using react but this of course this imports some tools specifically for react and now i'm going to paste in the slice and you can see it's export so we can export the slice export const api slice and then we use create api inside of this it's an object as you can see with the curly braces the first thing we do is define the reducer path again this is the default so if we didn't put this here it would still be okay because it would just default to that but i'm going ahead and including it and again you would need to rename that if that is not what you were calling it now then we have a base query and this uses the fetch based query that we imported and then there's a base url this should look very familiar to you if you're familiar with axios because you can define a base url with axios as well today we're using json server with our local dev environment so it is just our local host and then port 3500 as we specified for json server from there we're defining endpoints for the api to interact with and if you did work through my redux toolkit series then you are familiar with the builder cases that we had in redux toolkit and this is very similar so we once again pass in a builder and then we're defining methods to interact with the api so we're going to get all of the to do so i'm just naming this git to do's and we have builder dot query and then inside of that we have our query method and it once again is just an anonymous function that passes the slash to do's that would be attached to the base url it's going to request then all of the to do's with an http get method and then one very cool feature about rtk query is it creates custom hooks based on the methods that we provide so we could name this something else like get pizzas or something like that and it would create these custom hooks based on that name so this says use get to do's query but if we named this get pizzas it would be use get pizza's query so it's going to start with use and end with query and it's going to use whatever name we use for the method in between so down here we've just got export cost and we're destructuring getting the use get to do's query from api slice and now before we put this custom hook to use inside of our to-do list component i'll save this file we need to go back to the index.js some might do this in the app.js but it's just like the context provider if you were using the context api with react we need to provide our slice to the app so there's a couple of imports we need to use here and we're importing the api provider once again from redux js toolkit query and react and then we're importing that api slice that we created and exported so it's from features api and then we're getting the api slice so once we have those we need to wrap our app with that provider and i'll do that just by highlighting the app and then pasting this over so you can see but we're absolutely wrapping this app component in the api provider and then we're passing in the api to the api or with the api provider and it is of course the api slice that we created and now that our app can access this we can put that hook to use that we created so let's go to the to-do list component at the very top where i noted add imports with a comma or a comment i'm going to just paste in this import and it is the use get to do's query that we created right here so then we need to define that or use it inside of the component and we'll do that by just pasting this in and let's look at everything we get from this hook which is quite a bit we're getting data and we're destructuring all of this and i'm renaming the data to do's here and then we have is loading is success is error and finally of course if there is an error we find out what that error is so this looks a lot like a custom use axios hook or some other logic you may have seen used in a component before and once again this custom hook is being created for us so that's pretty awesome with rtk query now let's go ahead and use this to conditionally render some content i'm going to scroll down and where we find our content here and i left a comment that said define conditional content just paste this in quickly and we'll break it down we've got if is loading so if that's true we're just going to render this loading paragraph and if you have a spinner component that's a great place to put it as well else if is success meaning we've received that data for now we're just going to use json stringify and have it render to the page so it won't look pretty but we'll know we've got it and then the final elsif here is is error and then if that is true of course we have an error and we're going to display what that error is and you can see in the jsx we're just going to render that content so let's save all of this and now let's pull this over to the left visual studio code that is and see what this looks like okay we've got an error it looks like an import is wrong where we've got dot dot slash api slice so let's see what's going on i'll pull this back over so i can see the full thing and we'll need to scroll up to the top and yeah that's probably not where that is so let's find our api slice we needed to go up out of the to do's two dots not two slashes and then we need to go into the api folder then find the api slice and we were missing that api folder there in the import okay we should be good i'll drag this back to the left and yep we're getting all of that json stringify data here on the page so we are receiving all of the data okay let's pull visual studio code back over so we can view it in a full screen and now that we know we're receiving the data let's go back to that api slice and add our other methods okay we'll put a comma right after this get to do's method and we can paste in our next method here and that would be an add to do and notice something different about it instead of a builder.query it is a builder dot mutation and the rest of our methods will be mutations and that means we're actually changing the data we're not just requesting or querying the data but then we'll still have the keyword query right here and notice a to-do is being passed in because it needs a new to-do and then we're once again specifying a url but this time we're saying it is the url instead of just having a default query like we did above we're also saying what method we're using because it could be different it could be put or patch or delete or like we have here is post and then for the body of this request we're just passing in that new to do okay after the add to do let's go ahead and paste in the update to do and look how it is very similar to the add to do it's also a builder mutation it also receives a to do but notice the url is different here we're using a template literal so we can specify the specific to do with its id that we're going to update and we're using patch and not put you could use either one put is typically used as the method when you're replacing the full record and patches typically when you're just updating part of the record so i'm using patch right here we are passing in the to do though and then after that let's go ahead and put in the delete and to do that i'm going to scroll a little bit so we can see it all and here is our delete to do once again it's a mutation now we only need the id whereas the update needed not only the to do id but also the to do itself here we just need the id so we're destructuring that from the to do as it's passed in or whatever object we send with the id and then we're passing in that same url essentially but now we don't have to have to do dot id it just has the id here in the template literal the method is delete and the body only contains the id because that's all that is needed to delete the to do and now that we've added these new methods we can just scroll down here to our export const and we just need to add those other hooks that are created and notice once again they're not queries they are all mutations so they start with u's and end with mutations so we created an add to do method and so it's use add to do mutation the same for use update to do mutation and use delete to do mutation okay let's save these and head back to the to-do list to use all of these new hooks so instead of just the use to do's query being imported we're going to import in the other three hooks that were created as well and then under where we use the use get to do's query hook we'll paste these in and you can see we're just getting the functions from these hooks we don't really need to wait on the is loading is success is error and all of those things that we get from the query when we're reading the data this is something we're actually doing to the data so add to do update to do and delete to do and now the first function we'll put to work is that add to do so right here inside of the handle submit i'll paste this in and let's take a look we've got the add to do and all it really expects to receive is a to do so i'm creating a to do object here we're passing in the new to do we're setting the completed defaults and i'm just setting them all to user id one if you wanted to create a drop menu and provide different user ids you could the data has user ids in it so that's really up to you and how you want to do it right now the way this is set up every new to-do that is added would be attributed to user one and now let's add some more detail to our conditional content so where we have the json stringify let's replace that and map over all of the to do's to create something that's a little bit more like we want i'll hide the file tree so we can see it all but what we're doing is mapping over all of the to do's instead of the json stringify here and then we're returning an article and each article is going to have a key that matches the to do.id because there's lots of articles that will be rendered on the page one for each to do and then we've got a div here with the class name of to do and that holds the input and then that is the check box and then it also holds the label which is the description and that label has the html4 which we're also assigning to the id of the input so they're linked and using a label here instead of a span or a paragraph really helps with accessibility as well because it's linked to that check box other than that when we change we're calling the update to do and what we do there is spread in the existing to do then we overwrite the completed state because this change is for the check box and so that just sets the completed state to false if it was true or true if it was false and then of course we have a button here and the button has the trash can icon and that calls the delete to do and we're just passing in an object with that id so we've got id and then to do dot id right here okay with these changes saved let's pull our code back over and take a look at our app well this looks much better so let's see what happens if we go ahead and click on things it's not changing is it it's not updating see if it deletes doesn't seem to be deleting i wonder what's going on maybe we can add a new to-do and we'll say learn stuff and let's see if it's added it will be all the way at the bottom it's not at the bottom either so let's talk about what's going on i actually know what's going on but we needed to create this situation to understand it so back in the api slice if we look at these what is happening is the results get cached and we're not invalidating the previous cache and so it's not updating to show the new changes whether that's a delete an update or even a new to-do list or not a new to-do list a new to-do item added to the to-do list it's not showing any of that because we're still seeing the cached version of the data what we need to do is assign a tag to the cache and then let it know which mutations invalidate the cache and so then it will automatically refetch that data for us so the first thing we're going to do after the base query here is put in tag types and we're going to name this to do's and then for our get to do's method that we have here we need to put in a provides tags and say it's providing this tag of to-do's so then we'll need to invalidate the to-do's cache when we use these builder mutations below whether we're creating a new to do updating or deleting and i'll scroll just a little bit but we can add those right here by putting a comma after the query inside the mutation and then saying invalidates tags to do's and so let's do that for each one of these so we know the change has been made actually let's just do it for the update and the create and not the delete and we'll be able to see the difference once again so now let's drag this back over to the left and look at our to-do list so for the new one we could now say learn stuff press enter should work there we go let's see if we have our learn stuff at the bottom yep now we've got learn stuff twice because i typed that earlier with two exclamation marks now we've just got one so let's try the delete we're not seeing anything from the delete are we because it's not updating so it actually did create this earlier and it is actually deleting it now but our list is not re-rendering likewise we should go ahead and see a re-render of the list if i update an item yep and now that learn stuff disappeared because it really isn't in the current state of the to do's that we have at the api however trying to delete something did not cause the list to re-render whereas updating it did so let's go ahead and add that mutation back over here as well let's find that we've got the invalidate tags and that's what we want to add is to that delete mutation so we put the comma there and put in invalidates tags and save now we've re-rendered everything and now if i were to say delete this second one here our list re-renders and if i were to check then it re-renders and shows that new state as well likewise if i were to say hey for a new item and press enter we should now see it and this also highlights our last problem any new to do item we're adding is added at the very bottom of the list i'd rather see this in reverse order and see my new item at the top of the list we can also fix this because much like axios rtk query provides a transform response so there i can put in my sort function and i'm going to drag visual studio code back over to see everything for now so you can see this clearly we've got a transform response right after our query and here i'm just passing in the response and then i'm calling a basic sort function here for numbers in javascript because we're using the id numbers and to sort it in ascending order it would be a minus b but to sort in descending it's b minus a so i'll just save this and now we should be transforming that response that we get from the api and it should be sorting it in reverse order and we've kept the logic once again out of the component and put it over here with the api logic for rtk query i'll pull this to the left and we'll look and now my hay is at the top of the list i can delete that delete my learn stuff and even the new to do and then add another new to do and it's right at the top so overall you've got a quick introduction to rtk query here and we've created read update create and delete functions or methods if you will inside of our api slice provided that to our complete application and then of course implemented those in our to-do list component we have a nice little to-do list here and we've kept all of this api logic basically out of the components and in our separate api slice 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: 111,330
Rating: undefined out of 5
Keywords: react redux toolkit query, rtk query, react, redux, redux toolkit, redux toolkit query, react redux, react rtk query, crud, crud app, crud example, rtk query crud example, rtk query example, rtk query example app, react crud example, redux crud, redux crud example, redux crud app, rtk query tutorial, redux toolkit query tutorial, react redux tutorial, crud app tutorial, crud example tutorial, rtk query intro, rtk query introduction, rtk query react, rtk query app, toolkit, js
Id: HyZzCHgG3AY
Channel Id: undefined
Length: 24min 7sec (1447 seconds)
Published: Fri Apr 22 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.