React Query Tutorial for Beginners vs Redux, Axios with CRUD Example

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
react query performant and powerful data synchronization for react let's click on the docs it says react query is often described as the missing data fetching library for react and it makes fetching caching synchronizing and updating server state in react applications a breeze well today we'll find out if it's really a breeze as we build an example crud app we'll also compare react query versus redux axios and rtk query along the way [Music] hello and welcome i'm dave we'll be exploring react query as we build an example crud application i'll provide links to example source code and all resources in the description below let's start out with some of the versus questions react query versus axios first really you don't have to choose one or the other react query works well with axios so that's a bonus if you're already familiar with axios and want to continue using it now i'm on the page in the docs for react query that says does react query replace redux mobx or other global state managers well they highlight here that react query is actually a server state library that's responsible for managing asynchronous operations between the server and client where redux and other global state managers are for client state so that is a difference however redux modern redux now offers rtk query which fulfills the same role as react query so using one or the other there is more of a preference now i have previously provided a tutorial introducing rtk query and today we'll build the same app with react query and you could view that other tutorial as well and compare and see which one you prefer looking at our starter code repository i have created a react app with npx create react app i've moved away or deleted most everything that we wouldn't normally use so you see some of the extra dependencies gone however i did add in these font awesome dependencies because we'll be using a couple of font awesome icons today and if you download this starter repository of course you can do npm install and it will install all of the dependencies that are already listed we're going to add a couple more as well so i'll do control backtick type npmi for install and then react dash query also going to add axios so we can add both on one line and press enter and we should see those added to our dependencies i'll drag this down so we can see all of them and yes we now have axios and we also have react query here listed in our dependencies i'll close this i should also say in the description i will link to a completed repository so there will be two repositories the starter repository and the completed one now if we look over here in the file tree everything looks fairly normal i've removed some of the extra files that you get with create react app i also have a data folder in this data folder is a db.json file and this json file has a lot of to do's in it we've got to do's and then an array with objects and each object is a to do i got this json from the json placeholder website but we're going to use json server locally to do a mock api here during development and again we're recreating the exact app that was created in my rtk query introduction tutorial because i'd like you to be able to compare apples to apple so to speak that we are creating the same app and you can see which one you like best as well so with that said that is our data we're ready to start in the index.js file oh i should highlight i've also provided some css and i did provide a little bit different css than i did in the rtk query just so the different application actually the same application would look a little different for you okay now in the index js let's go ahead and complete some imports that we need right away and the first is query client and then we can hit tab and we get that from react query we also need query client provider and after we have both of those we can import one other thing and here we'll say it is react query if i could spell query correctly each time dev tools and notice tools has a lowercase t there and this comes from react dash query slash devtools and after that our imports are complete now we are using react 18 and we are leaving react strict mode in so underneath react strict mode now let's add our query client provider and press tab well no we didn't quite finish it there we go and now let's get the closing query client provider and put it after the app component and then above before we're in the jsx we actually need to create a query client and this is camelcase lowercase q uppercase c and we'll set that equal to new and now query client with a capital q and a capital c so we've created a new query client there and we're going to pass it into the query client provider with the value of client so now we pass in the query client that we created and that will be available to our entire application now we could just stop there but let's go ahead and put in the react query dev tools as well so here we put react query dev tools and we say initial is open and then we can just close that with the slash greater than symbol now the react query dev tools is different than reactive tools that's dedicated to react query and it will only open when we're in development mode so you don't need to worry about having this here for production this will only occur or will only open up or be available to us when we're in development mode so we'll leave that there and of course we'll come back to that later when we launch the application now let's highlight the source directory and create a new directory inside named api lowercase and now inside that we'll create a new file to do's api and it can start with the lowercase t and then camel case for the api with an upper case now we'll do everything we plan on doing with axios in this file so we need to start out by importing axios and then we need to create our to do's api and set that equal to axios.create and now parentheses and curly braces we set the properties so we'll set base now this is important that url is all uppercase or axios will not recognize it i have learned that the hard way and now we'll say localhost 3500 because that's where we're going to run our json server instance okay after that let's go down and say export const get to dues and now this will be our read function in the crud acronym from create read update and delete and here we will request all of the to do's so we'll set a response equal to await the to do's api that we just created and use the get method and we'll get the to do's endpoint and then after that we need to go ahead and return the response dot data that we get from axios after that let's create the create method and that would be export const add to do we'll set this equal to an async function that receives a to-do and now inside of this function we can do this in one line it will be return await once again the to-do's api dot post and it will once again hit the to do's endpoint and then we pass in the to do now after that the next two methods are very similar we have an update and delete so i'm going to highlight this press shift alt and the down arrow to create each one and give a little space between and the first thing i'm going to do is get the methods right so we've got patch now for the update if i need to highlight that and type over it so to do's api.patch the last one will be to dosapi.delete but then we need to make some other changes here instead of add to do this will be update to do and here instead of add to do this will be delete to do now we do receive the to do for the update but then we need to change the url endpoint a little bit so we'll change this into a template literal string and it will go to to do's but after that we need to specify which to do we're updating so this will be to do dot id as part of the url so we're getting a specific to do to update this will also be similar here as well so with the delete we can once again turn this into a template literal but after this we're actually going to destructure what we receive here and just get the id for the delete to do and once we have the delete to do we're going to go ahead and press slash again and then put the id right here in the url and then of course we're not receiving the full to do this will also be an id so let's save that and then underneath here we can go ahead and say export default and have the to do's api just in case we would want to expand the application and for some reason we needed to export this we won't be using it today but it's a good habit to go ahead and have that available now we have completed our crud methods with axios and we have our instance up here as well let's go ahead and highlight the source directory once again and let's create a new directory inside of it named features and then inside the features directory we can create another directory named to do's now inside the to do's directory let's create a component name to do list.js now i have react es7 snippets installed so i can type rafce press tab and i get the outline of a basic functional component but we're going to add a lot to this today so let's start with the imports at the top we need to import use query and this is going to come from react query but we also need use mutation i could spell mutation and then we need use query client that all comes from react query then we need to import and i put impot import all of the crud methods we created with axios so get to dues and then we also need add to do update to do and delete to do i'm going to press alt z just to get the code to wrap if it ever gets to be too long on an individual line to see okay after that we're also going to use font awesome so we'll have font awesome icon imported and then we're going to use a couple of specific icons f a trash for a trash can and we're also going to use fa upload so those are the two icons we need then we're going to import in use state and that just comes from react itself okay now that we're at the end of our imports we're ready to start in on the component the first thing we'll do in the component is define our state with a new to do and set new to do that's going to be equal to use state and an empty string after that we need a query client once again whoa i put that on the wrong line there we go now we need to define a query client once again our query client this time is going to be equal to use query client and that is a hook and that is delivering the query client that we were providing here in the index js as we passed that query client in the provider so now we're actually getting that here in a component from the hook use query client okay after that we need to say const we're going to d structure and i'm going to put these values on separate lines so i'll scroll up for a little more room and say is loading comma is error comma error and then data and we're going to rename the data to do's now after we have that we'll set all of this equal to use query and we need to name the cache that is stored and this cache is going to be named to dues and react query provides that cache after that we need to pass in our method so that is get to dues and we should be finished there okay after this we need to add the mutations that we created as well this would be the add to do the update to do and the delete to do so the first one is add to do mutation that we'll define let's set that equal to use mutation and then we pass in the add to do method that we created and then we put in curly braces and look for on success and then on success has an anonymous function and inside here i'm going to leave a note so we know what it does it invalidates the cache so it would invalidate the to do cache when we add a new to do and then it triggers a refetch so we get the to-do list again with the updated to do in it so it would have fresh data and then we call query client dot invalidates queries to do exactly what we were just talking about and we invalidate that to do cache right here now the other mutations are going to look much like that so i'm going to scroll up and then highlight the add to do mutation shift alt and the down arrow twice to create two more and i'll put space between each one so now i can highlight add and press ctrl d to get the other instance of add and switch that to update and this is the same after that on success we once again want it to invalidate the deduced cache so it re-requests the to-do's and we get the updated information and then let's switch the ad here and highlight that and we'll switch this to delete to do mutation and it would be the same we'll have it invalidate that to do's cache and it will refetch so we have the most up-to-date information and now we have integrated the axios methods the cred methods we created with react query so now let's go ahead and put one of the mutations to work by creating a handle submit function and this will be triggered when we actually handle the submit of the input for the new or the new form actually where we input a new to-do item so it's going to receive an event because it's the submit event from the form and when that happens you don't want the form to reload the page so we immediately call event dot prevent default then we'll have add to do mutation and we call mutate so it's add to do mutation dot mutate and then we pass in the to do just for this example i'm going to give the credit for all new to do's added to user id 1. after that we'll take the title and here we'll just pass in the new to do and then we'll have a completed property and all new to do's will be false they still need to be finished so after that we have passed in the new to do information and then we just want to set the new to do state back to an empty string i'm going to scroll up once again and right underneath our handle submit function i'm going to define the new item section and i'll just go over this with you this is the form where a new item is submitted and i'm storing it in the variable new items section that we will pass on to the jsx so the form has the on submit handler so it looks for the submit event and calls handle submit we have a label for the text input and the input is tied to the new to do state and when we get a change event it sets the new to do state and then we have a button which is a font awesome icon and it's the upload icon so when the form is submitted it's triggered by this button as well as just pressing enter as any form could be submitted that way as well that's our new item section now let's scroll back up to review quickly our query that gets information has an is loading value and is error value and then if there is an error we get the error and as well as the data so we can use these to conditionally render our content so we'll scroll back down under the handle submit and under the new item section and let's conditionally render our content here so i'm going to have let content and then on the next line we can say if is loading is true then we're going to set content equal to a paragraph that simply says loading now we can continue this with an else if is error is true then we could set our content once again equal to a paragraph and inside this paragraph let's take the error dot message that we get and that would display whatever error message we possibly get and then after that we could just have an else so is loading is not true and is error is not true so we should have the content we expect here and to start off with we'll just set the content equal to json.stringify and pass in the data that we are getting back actually the data is now named to do's because we renamed it so let's save that and then for our jsx at the bottom i'll remove what we have here for the div and we'll start off with a main element and then inside that main element we'll put in h1 say to do list after our heading here then we'll put our new item section so we have the form to add new to do items and finally we'll put our content underneath now remember currently it is just the to do's inside of the json stringify so it won't be that pretty but it is what it is to start out with and then we'll change it and improve it so now control backtick to open a terminal window i don't think we started json server yet so to do that you could install it globally which is what i have done so i if i were to install it globally again i would put npm i json-server dash g if you want to do that you don't have to you can just launch it with npx and then the commands that i'm going to type without npx so i'm going to delete npx but if you don't want to install it and just want to launch it start with npx first and then type this json-server dash w for watch and then we're looking at the data folder and then the db.json file then dash p for port and 3500 i'll press enter it should find our to-dos yep that's the resources and it's available at localhost 3500. now i'm going to open a second terminal window and here i'm going to type npm start to launch our react app pull visual studio code over to the left of my screen and we should see our app here shortly and we'll see what we get we don't have anything yet because i forgot to import the to-do list into the app component app.js so we'll just close the terminal quickly and then we can fix this by saying import to-do list and then we just want to return our to-do list below so instead of the parentheses and the div within we'll remove all of that and return to do list close it out and save that should change what we see now yes it did so now we have everything here on the page we expected here is our new to do entry our header here is all of our stringified data also i'd like to draw your attention i'll pull this over to the react query dev tools that you can experiment with they're right here in the bottom left if we click on that it opens it and we can see the dev tools here and it's still scrolling the page but overall it says we have some stale to do's at this point we clicked to do's and we got some more information now you could invalidate everything manually refetch you can look at the data one thing i particularly like is the query explorer well i closed it and it just collapsed on me there we go bring it back and you can see a lot of things about the query including the state and the data that you have in here the initial state definitely interesting things to look at so there's other values for example besides the is loading there's is fetching is paused things like that that you can explore and learn about so go ahead and play around with the react query dev tools as well okay back to the application it is working it just doesn't look like we want the finished product to so we'll grab visual studio code bring it back and we have a little more work to do here in the to-do list i'm going to scroll up as high as i can and we're going to replace this json stringify content with more formatted content and i'll just review this with you so we've got the content once again setting it equal to to do's dot map now as we map over each to do and create an article from each to do so we're giving each article a key which is the to do id and then inside of that we've got a check box and this is where we use the update to do mutation we once again say dot mutate and we spread in the existing to do and then we just choose the opposite of whatever the completed value is to overwrite the current completed value so that is the check box since whether it is completed or not then we also have a button at the end of the article for the to do item and this button is the trash can which should delete the to do and we can see in the on click we call delete to do mutation once again dot mutate and then we just pass in the id of the to do and if you remember our crud method that was the delete method all it needs is the id so that should be accurate let's save this and drag this back to the left and see if our application is working as expected and i believe it is what we do have though is one issue that i want to point out let's make sure everything else is working so that unchecks and checks let's see if we can delete it yep it's gone too so that works but when we add a new to-do as i'm about to and press enter that should work but we don't see it here i think it's all the way at the bottom of the list yes there is our new to do so really we want new to-do's to be at the top and there's something we can do to change that another feature that we haven't talked about in react query yet and that is being able to add a selector so now in our use query that is getting the data after the get to dues we can put a comma and then we can put in our curly braces and define our selectors so we'll say select and this is our area to transform data also if we want to and that's what we're going to do right now so i'm going to take the data and sort it so we'll pass our data into this function we'll call data sort and now we'll have a and b is in a typical sort function here and i'll have b dot id minus a dot id and this will sort the data in reverse order are to do's in reverse order so we can save that and now if we pull this back and look at the application again now we see our new to do at the top and we can delete that and say hey and enter that and now it's at the top so this is the order we wanted so now just a final word between react query and rtk query which both solve the same problem rtk query does integrate with redux but in itself it's not a global state manager it's doing the same thing react query does and you can use it that way what about when to use react query well it's kind of a preference for both but what i have noticed is if you're used to axios such as the crud functions or methods if you will that we created here inside of our api for with axios that might be an easier transition rtk query is more opinionated a little more strict and tied directly into redux not every application needs redux state management either so there might be a middle ground here where for some smaller applications you might be more comfortable unless you need redux you might be more comfortable with react query myself i really like rtk query and i like using redux and they go together so well that's probably what i'll continue to do unless i'm using or creating an application that i believe does not need redux at all and then i may use react query because it's definitely an upgrade over just using axios by itself and it has many of the features that i'm used to from rtk query but we can just implement that with react query so it comes back to your preference overall you get some of the same nice features though and you get cache so you don't have to create your own use axios hook you already get an is loading state and is error state you get the mutations you can invalidate queries and you can get more specific here too we could look at individual to do's if we were just updating one and wanted to look at a page or just requesting one at a time instead of the full list so there's much deeper dive available to react query as well and of course you know you can go deep with redux and rtk query i like them both is the final verdict and let me know what you like in the comments especially after you check out both tutorials the one for rtk query and of course this one that has created the same to-do list 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: 83,132
Rating: undefined out of 5
Keywords: react query tutorial for beginners, react query tutorial, react query for beginners, react query, react query vs redux, react query vs axios, react query vs rtk query, redux, axios, rtk query, react query vs rtkq, react, react js, reactjs, react tutorial, react for beginners, crud example app, crud example, crud, react crud, react query crud, react js crud, reactjs crud, crud app, crud application, crud tutorial, crud for beginners, axios crud, react axios, React query axios
Id: lLWfZL-Y8lM
Channel Id: undefined
Length: 27min 36sec (1656 seconds)
Published: Fri Jun 03 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.