React Query - Full Tutorial 2024 🔥🔥

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
so react query or tane query is a powerful asynchronous State Management for typescript and JavaScript apps what that basically means is that this is a data fetching library and it helps us to fetch our data manipulate our data and it comes right out the box with features like caching ref fetching pagination and so much more so let's go on and see how we can use react query to fetch and manipulate data in a reactjs applications efficiently so I've opened vs code over here I'm going to quickly go to the terminal and initialize a new react app so I'm going to say npm create wheat at latest and it's going to ask our project name and we are already inside of this react query tutorial folder so I'm going to press dot to create a folder over here I'm going to select react and JavaScript and it has quickly initialized a new react app for us over here let's go on and install all of the dependencies by typing npm install okay we have successfully installed the dependencies let's run npm run Dev so that we can see our app running and there we go our app has successfully started what I'm going to first do I'm going to clear up everything that we don't need first of all delete this assets folder inside of app.jsx I'm going to clean it up just going to remove everything over here just have a div which says subscribe to roadside coder which you should if you haven't yet and I'm going to clear all the Styles inside of index CSS and app. CSS great let's run it again and awesome we can see subscribe to roadside coder over here now how do we go on and install react query let's go on and read the docs inside of the installation okay npm install at tquery SL react query okay I'm going to open a new terminal and paste this command over here okay so this has finished installing and I'm going to install one more uh package over here npm installed Json server so what is this so to test uh react query we're going to need some apis as well right so if I go on to Google and search Json server and we have this npm package over here so what this basically helps us do is it helps us create some mock apis from our Json data so what I'm simply going to do let just close this up I'm going to create a folder over here called API and instead of it I'm going to create a new file called data. Json and here I'm going to paste my Json data which contains two things first is this posts array with all of these objects inside of it and the other thing that it contains is this tags array so that it creates two apis for us and I'll show you how it does that and if you want this data as well you can click the link in description down below and go to my GitHub repository and copy this data from there so let me show you all we have to do we have to type npx json-server and we have to locate this data. Json file so this is inside of SRC SL API /data do Json and sometimes you might get this error as well so just remove this tags from here and just run this again and when it runs successfully just add this tags back over here so yeah we get both of these endpoints and if you click on any of these endpoints you're going to see we get this API and point over here if I say tags you're going to get a tag mock API endpoint and not only the get request it provides us a lot of other requests as well like post put patch delete Etc we can make a post request and we can add a new post inside of this array of posts over here so this is an awesome mock API Library so let me just close it up and now that we have installed our react query let's go on and set it up so inside of our main. jsx I'll bring in something called query client from react query and this will be new query client and I'm going to assign it to a variable query client now what we're doing over here is we're creating a new instance of our react query or Tan St query and we will wrap our whole of our app inside of this so over here I'm going to import something called query client provider and I'm going to wrap whole of my app inside of this let me just close this up and this will take a client which is going to be this query client over here okay that's all we needed to do to set up our react query now I'm going to go to app.jsx and make my first API request by using react query and what I'm going to do I'm going to say use Query now use Query is a hook provided to us by react query and let me show you what it does so first of all it takes an object inside of this parenthesis and it takes a bunch of things first of all a query key so query key is a unique key key that you provide to each and every query so that we can identify it uniquely so for example for this one I'm going to say posts and the next thing that is going to take is going to be a query function inside of it where we will make our asynchronous request or where we will fetch our API so instead of just writing the code over here I'm going to create a new folder for api.js and over here I'll write all of my logic or all the helper functions for our API so let me just quickly bring them in so this is very basic over here inside of this fetch posts we're just fetching this endpoint which I already showed you and this underscore sort equals minus ID is basically sorting it from in the reverse order so that later on when we add a new post we can see it at the top then we have this fetch tags API call and this add posts API call which we're going to worry about later right now we just only concerned with this fetch posts so let's just take this fetch posts function and just paste it over here and let me just import it so basically this will fetch all of the posts return this with a promise and the list of our posts and this right over here is where the real magic happens it's going to give us a bunch of different things so let me show you if I press control space over here you can see we have data data updated at error failure count is error is fed is loading is paused is pending we have bunch of different uh options over here so let's take the data and is load loing and let me just quickly over here console log this data and is loading so let's go on back to our browser open up our inspect and if I just uh refresh this you're going to see first of all the loading was true and data was undefined still true still undefined and as soon as we get the data loading was false you see earlier we had to handle all of these things we have to create a use State and we have to say loading true then loading false we that was a very big big headache right so all of these things come right out of the box we can have something like is error we can have error State what actual error we have we have we can have a status let me show you the status so if I say status over here and refresh this see initially status was pending then it was success so now you might be thinking how will I know what are all the things that this contain and how they work so it's simple just go to the documentation and um let's search for use query and yep you see we have the complete documentation with all of the things that you need to know right over here you can go through this docs highly recommended so that you can get more information about it but as this video moves forward I'm going to show you more and more features over here and you know what I'm going to create a very simple uh react app over here for fetching all of these posts efficiently I'm going to show you how the posts are casted how you can add a post inside that list how you can add pagination features Etc so let's go on I'm just going to quickly remove this code over here and create a new folder for components instead of this I'm going to have a new file for post list. jsx and here I'm going to say ra a fce and if you don't know how I did that I have an extension installed over here called es7 react Redux react native Snippets and you can install this as well to make use of those Snippets so yep I have created this component over here let me just uh import it right below this post list and let me just uh import it from SL component SL poost list cool let me just remove this from here this as well if you go back to our browser you can see post list is right over here let's just add a very basic CSS style our body for font family Sans serif this is better okay now inside of the post list I'm going to do the same thing I'm going to fetch all of our posts so I'll say use query I'm going to say query key posts and you might be thinking why is this an array so let's say there are some things that are dependent on this uh query function so for example if I say query function over here and I call this fetch posts right now inside of this first posts later in this video I'll show you how you can do pagination as well so for that we have to pass the current page right to fetch all the posts from that page so we have to declare over here that yeah page is one so that it creates a unique query for that particular page and this helps react query for caching the data uniquely for that particular page so let's not worry about it at this moment so yeah okay and it gives us a few things I'm going to take data I'm going to take is error is loading and the actual error and inside of this div I'm going to first of all have a class name over here of container which I'm going to style it in just a moment and inside of over here I'm going to say if is loading is true then I'm going to show a loading indicator so let's have a P tag for loading and let's have an is error tag if the error is there then I'm going to show error. message let me just add an optional chaining over here just in case error is not populated and right below this I'm going to render all of our data so I'll say data do map and let's rename this data to post data so you do that by using this colon just like this so post data I'm going to take one single post I'll say return a div over here inside of this div let's see what do we have inside of our data we have a title tags and ID okay so I'll say post. tile and also we're supposed to give this a key as well else it will show us error post. ID okay okay below this I'm going to render all of the tags that are related to that particular post so I'll say post. tags. map tag and I'm going to have a span tag over here inste of this we will render our tag and let's just give this a key as well of tag okay let's see what do we get okay we're getting the title and we're getting all the tags over here as well awesome let's go on and add some uh bare minimum Styles over here so what I'm doing over here is for our container class that is this I'm going to say some display Flex Flex Direction column to render it from top to bottom and some gap for post simple some display Flex some align items to the center so that they can be aligned at the very center over here and I haven't given this class I forgot so let me just say class name equals post and now yeah so we're just giving it some background color some border radius and some padding and for same for our tag as well some background color some padding border radius and margin left to create some spacing between them just some basic styling let's just give this some title as well so inside of my app.jsx I'm going to create a H2 with title of let's say my posts and this will have a class name of title I'm going to give this a style as well which is going to be some font weight some font size text transform and text align Center some very basic Styles okay cool then so we have already seen how we can fetch all of the data by using react query or this use Query hook over here now let me show you a very powerful feature of react query so if we go back to the documentation if we search Dev tools so you see it comes with a react query Dev tools as well let me just um copy this line and install it and I'll show you let's open a new terminal paste it over here okay this installed let me just close this up and now inside of our main. jsx I'll just import this react query Dev tools initial is open equals false so right below this let's import it as well from tan st/ react query Dev tools and now if I go back to my browser uh this is giving us some post data is undefined okay so post data let me just add optional chaining over here and yeah everything is fine now notice this little circle icon over here let me just uh move myself so yeah you see this little circle icon over here if you click on it you're going to see we have this whole Dev tools over here so if you click on this post squarey that we've been making up until this point you're going to see all of the data that is inside of it it's going to show you the current status if it's a fresh data if it's a stale data I I'll explain what this stale means and but basically it means that this has cast this data when it has became outdated we can refresh it from over here it's going to just refresh it right here and if we refresh this you're going to see we get this loading indicator as I showed you earlier so awesome we've already seen how we can fetch our data by using react query now let's see how we can change our data how how we can make posts requests by using something called as mutation in react query so for doing that I'm going to import a hook from react query called use mutation but before that if you're preparing for your front end interview and you would like me to help you in your front end interview preparation just click the link in the description down below and book a one-on-one call with me we're going to discuss tips tricks I'm going to give you a lot of resources I'm going to design a proper road map tailor to your situation which is going to help you out a lot in your front end interview preparation so click the link in the description down below and book a one-on-one call with me now inside of over here this takes an object as well and inside of that object just like this query function we have a mutation function over here and this takes a function just like fetch posts for making a post request right so this was for our get request and for our post request I have written this helper function over here it's just taking this endpoint and it's just making a post request with whatever post that we provide to it so let's just take this and add it right over here and then this returns us with a few things like context data error and a lot of things but what we're concerned about is this muted function over here so this muted function is what we will call to make this post request so this add post obviously has to be provided this post right so we have to call this mutate function with our actual post that we're supposed to add inside of our post request and this will automatically know that this has to send it over here okay and then this gives us a lot of things like is error and is pending to show that our request is pending right now our actual error so since this error is uh colliding with this error over here I'm just going to say is post error and this error I'm going to name post error and I'll also show you something called reset in just a moment let me just write it over here so that I don't forget okay now let's create a UI uh input field where we can you know type the data and press enter to add this post to our list of posts so let's create a form over here and inside this form I'm going to have a input field of type text it's going to have a place folder of enter your posts class name of post box and name of title so that we can use this name inside of our form data and below this I'm going to have some checkbox which will show us all the tags that are inside of our data right so I have already created this API for fetching the tags as I already showed you with the help of Json server so I'm going to take this fetch tags and I'll basically create another query over here so use Query and this query will be for our tags so it's as I already showed you this will have a query key for tags and query function which will take this fetch tags let me just uh import it cool this will return us with the data and let's rename this data to tags data let's render this tags data over here right below this so inside of the div called Tags I'll just simply do tags data. map and inside this D I'm going to render an input of type checkbox and a label HTML for tag which means this label is related to this input field because we have given this ID of tag over here and obviously we're going to give this some name which is going to be helpful for our form data so let's go back and see how this looks okay it's not looking very good let's just style it a little bit but before that let me just add a button over here for posting as well so this button will basically say post okay let's just go to app. CSS and add some Styles over here so inste of the container for the form I'm just giving a display flex and flex Direction column so that everything renders from top to bottom and for our Button as well I'm just giving some basic styling some background color and all for our post box some padding font size border radius Etc some border bottom and Border n so that we can only see the bottom border so that it looks good and for our tags just some display flex and some space around them so let me see okay this looks very good we can enter our post over here and click on this post button to post it cool then let's go on and add the logic so right over here I'm going to say on submit and I'll create a function inside of it called handle submit let's create that function over here handle submit and this will take an event and inste of this I'm going to get all of our form data so I'll just say const form data equals new form data will take e. Target and then we have to get this input and all this tags data from inside of it so const title equals form data dog and what's the name of our input it's title so I'll just say title over here and similarly for our tags as well I'm going to say const tags I'll say array. from form data do keys so let me show you something why I'm doing this so over here you can see we have this input field with the name tag so all of these tags will have different different name so like classic English fictions but we want them all inside of one single array so to do that what we're doing over here is I'm saying array. from which creates an array from an it aable object so this will create an array from these objects so I'm taking all of these Keys like all the keys inside of this form data which will contain these Keys as well and what I'll do I'll just say simply filter do filter and I'll take each and every key and I'll say form oops form data. getet key if it is equals to on so this checkbox has two properties on and off right so if it's on then obviously this is a checkbox and we want that checkbox which is on so if we go over here and say console log our title and tags you're going to see set the inspect if I type anything over here and click on wait click on post oh my bad I forgot to do e. prevent default so that it doesn't refresh us our page okay let's see again we type anything and post yeah you see we're getting the title and and the array of all the tags cool then here let me just add some null check if title is not there or tags is not there just just return else we will call this mutate function over here let's see how this works now so I'll just say let me just remove this I'll just say mutate and instead of this this will take an object where we will provide both of these so I'm going to say title and I'm going to give us give this a tag so I've given this uh title and tags over here because inside of our API if you see in our data we have this exact title and tags if we hadn't given this title like we would have given this post title then would have we would have to do like title col and post title so that's why I just gave it title name so it's easier for us and also let's give it some ID which let's say post data whatever the post data is do length I'm going to add one to it that's all and after this mutate is done I'm going to Simply do e do Target do reset so that we reset our form so okay let's just say new post one and let's select something and post it h nothing happened it wasn't added to the lists of our post let's see what uh what's going on if we go to our post request okay we get the response yep the post was added let's just uh refresh our page okay the post is here but but why wasn't it uh you know updated right away what's the reason so it's because of the caching feature of react query so let me show you if we add something again let's say new post two select something over here and post so see in the mutations we have made a mutation over here but in the post it shows that this has gone stale so to refetch it we need to invalidate this data and when we invalidate this data notice over here if we invalidate this data yep you see it fetches this data again and displays it inside of our UI so how do we do that with our code so inside this uh use mutation it gives us a bunch of functions like on success that is after our query has succeeded it's going to call this function over here with few things like our data which has been returned our variables that we provided it which were these variables over here and the context which comes from over here so it has one more function called on mutate so on mutate runs before this actual mutation happens and on success runs after the mutation has happened so this is for making some changes before it so if you provide something let's say return ID equals 1 over here it's going to go right inside of this context over here so you can use it according to your use case so now as I was saying on success what I want to do I want to invalidate this query over here this posts query over here now instead of this on success I'm going to take a query client uh for which we have to import it from our use Query client hook so I'm going to say use Query client and this gives us the access to our query our react queries internal API from where we can use some functions so I'll say query client equals use Query client and we're going to take this and over here I'm going to say do invalidate queries now this takes a few things first a query key which will be posts because this is the query key that we're look to invalidate right so let's see if we go back to our browser and if I say new post 4 and let's click on over here and click on post yep you see our queries were refreshed and updated right over here awesome now for this query Cent as I me mentioned earlier we can have more than one thing inside of this array right like for example if we have given a page equals 1 we can say comma page to one and this will invalidate that particular page over here if you just give it this posts then what this will do it will invalid every single query with this posts inside of it with this posts key inside of it so to avoid that situation we can do exact to be true so that it can only invalidate this query which contains only the posts inside of the array this also takes a predicate key which includes queries matching this predicate function so what we can simply do over here is we can write a logic for example we can have a function here like this so what this will basically do is it will take uh the query and it will say query do query key first one is posts and the next one is Page more than two so all of the pages more than or equal to two will be invalidated so this is more of some high level stuff so you can just go on the documentation and have a look at this it depends on uh everyone's use cases so it's not that much frequently used so now next uh yeah let's talk about these functions so we have on mutate on success similarly we can have on error function as well if we want to do something on error we can have an on settled function over here as well which will run no matter if our query was succeeded or it failed so this error it takes error and variables and contexts and unsettle takes everything data error variables context Etc so let me just comment these out for now so that you can explore them later on now this uh use mutation returned us with these things like is error is spending and stuff right so let me just say uh they take this is pending and just U add over here alongside R is loading so that when we are making our you know post request as well it will show this loading apart from that uh we need to show error message as well so let's just duplicate it I'm going to say is post error if that is there that is this one I'm going to take this post error and render it over there or you can also say something like unable to post right so let's just uh do something with our API let's add some s over here so that we get some error while posting so let me just write something and click on post yep you see unable to post now I want to reset this as well I want to click it so that I can reset this error so for that we have something called reset so I'll take this reset function from here and on our error over here let's just say on click oops on click this will call this reset function and now let me show you if I click on unable to post yep it's going to reset our error and the state of our app basically now these are some of the few functions that I've shown you from uh Muse mutation but there are obviously more functions and uh variables that it provides to us so I would highly recommend you to go and read in the docs about it now I know one thing that uh you might be thinking is what is this stale and caching and this fresh all of what what is going on over here so let me explain you so when we fetch a query by using react query it marks that query instantly as stale that this is no longer Fetch and we need to invalidate this query to fetch it again so let me show you what the role of this stale thing is so if I just go on to my app.jsx and uh let's create a button over here which will say toggle right and I'm going to create a state over here use State we'll say toggle by default it's going to be false I mean true let's import use State and over here when this toggle is true only then we will show this posts list okay and I'm going to say on click set toggle to not toggle so that it inverts whatever is inside of this toggle so yeah let me show you if I just open inspect over here go to network tab let me just close this up yeah now see if I click on toggle it just unmounts it from our react app if I click on this again you're going to see we see our posts but after the API request is made so after this posts API request is made and this tags API request is made what if we want this to Cache this data we we don't want to fetch the post again after this toggle is done right so what we can simply do let's say for our whole app if you want to do this inside of over here inside of main. jsx I'm going to give this query client some options let's say default options and for all of our queries oops inside of our object I'm going to say queries inside of another another object I'm going to say stale time so let's say if I want it to be cast till 1 minute so I'm going to say th000 that is 1 into 60 uh seconds so let's see now you're going to see if I just clear it up if I click on toggle and click on toggle again you're going to see this has not been fetched because these are still Fresh So if I click on over here you're going to see it shows both of these are fresh over here but obviously this doesn't make sense for our post but for our tags it does make sense because they are not changing forever right so okay instead of over here what I'll do I'll just go to my posts list and this use Query has a key as well which is taale time so for our tags I'm just going to say infinity now you're going to see if I clear this up see this became stale and this is still fresh and this will forever stay fresh as if I click on toggle and click on toggle again see the post was fetched but the tags was not fed because we made it fresh all the time so this will not get stale now we have more options over here which you can add inside of this or you can add right over here as well for one single query like for example GC time so GC time so the time in milliseconds that the unused inactive cash data remains in the memory so let's say if we have casted some data if we have added a stale time over here here so if I make this GC time as zero this will never be cast and it will forever remain stale and actually there's one more function over here that is refetch interval if we provideed something let's say 1,000 that is 1,000 into 5 let's say so it will be fetched every 5 seconds so you see every 5 seconds it's going to make it in like it will invalidate it and you see it's fetching it if you see you're going to notice yep you saw it was fetching and then instantly it uh was stale so yeah we don't need this right now okay now let's talk about how we can add pagination inside of our app so okay what I'll simply do right above these posts data I'll create a div with Pages class name inside of this I'm going to have a button which will say previous page and another button which will say next page and between these I'm going to have a span tag which will say current page and it will play the current page basically or we can just say page over here whatever the page is so yeah let's create a state for it and did you notice something we have built this much of app and we haven't even touched use state or even use effect so this is the power of use Query it comes with all of these features right out of the box now we have to maintain our page uh number somewhere that's why I'm having this uh use State over here so by default let's keep it one let's let's import use State and let's see it in our UI okay previous page one next page cool let's just give this some uh basic Styles so over here I'll just say justify content to Center and display flex and just give them some gaps and align items to the center so yeah now what we will do we will take this page variable and we will provide it to our query so over here I'm going to make this uh an arrow function and just provide it with this page so that this fetches our page and as I mentioned earlier if you're making some change inside of this function over here and we're providing it some outside variable like this page over here then we're supposed to inform use Query by giving it inside of this query key so I'll just say comma page and this will form a new query because of this but let's just uh make some changes inside this fetch post so it will what it will basically do it will take a page and here I'm just just checking if the page is there then just say underscore page equals page and per page we're supposed to display five items so all of these are just for Json server for adding the page Nation inside of our app so yeah let's close this now and let's see okay this is breaking why it's not a function okay let's see the network let me just refresh it inside of our posts in the response oh okay so right now we were getting all the arrays uh the data inside in the form of an array but now we're getting more information like next page is second previous page is null right now because we're on the first page right total pages are seven and then we're getting this data so all we have to do simply is this post data when we are rendering it over here I'm going to say dot data and let's just add optional chaining here as well and now instead of just doing this post data. length I'm just going to post data do data. length just add a optional chaining here as well and let's see okay things are looking good right now and inside of our Dev tools you can see the posts and the page one so it will now cach the data with respect to that particular page and I'll show you when this page changes you're going to see the page two we're going to see entirely different query over here cast inside of it so let's see so over here inside of our button I'm going to say simply on click and here I'll say set page and I'll take the previous page or let's say the old page and I'll say math. Max old minus1 comma 0 so when we click oops not old I mean old page so when we click on this previous page button it should go to the previous page right so I'll say hold page minus one but it should not go beyond zero right so that's why we are doing math. max if it goes beyond zero it will just take zero over here and also if there is no previous page then we're just going to disable this button right so I'll say disabled and I'll just use this so we have this priv over here right so I'll just say post data. priv so not actually not post data. prve so if it's null then it's just going to be disabled so if I go back yep you see we cannot click on it it's disabled now let's take care of our next page button so similar to this I'm going to have an on click over here in this button as well but there's going to be a few changes first of all I'm not going to have this math. Max And all I'll just say old Page Plus one but we're not going to do this right away so first of all let's just add this disabled condition here as well disabled and for our next let me just add optional chaining over here so that this doesn't break okay now let me show you something if I go back to my browser and if I click on next page you're going to see okay it's fetching the page next page again it's fetching and see the other Pages data is being cast over here see over here these pages are being cast but as soon as I click on previous button they're going to be feted again we don't want to do that right so we want to keep them fresh for some time so what we can simply do over here inside of our usequery I'm going to Simply say stale time and I'm giving the stale time of 5 minutes so now you're going to see if I clear it up if I refresh this app click on next page now if I click on previous page it's not going to make another API call even for next page as well so y this is the power of react query and there's also a option over here of placeholder data where you can add this keep previous data function to keep the data of the previous page stored inside of our cache but I personally feel like this this tail time is much more effective because you can customize it according to you now apart from this sort of pagination you can do infinite scrolling over here as well like for example if I went over here and if I click on load more it should load more data if I click on load more again it should load more data so that is a very interesting feature of this uh react query so what I want you to do is I want you to go inside of the documentation and try to explore what infinite quering is all about and it has a hook called use infinite query which is similar to use query but more tailored for doing infinite page Nation inside of our react app so if you're able to do it great if you're not able to do it I have uploaded a reel on my Instagram explaining this whole use Query hook and how you can use that to implement infinite pation inside of a react app so open an Instagram app right now and search roadside coder and click on this highlight over here and you're going to find the Reel hosted inside of it now the next steps for you we have something called use queries as well which enables us for fetching bunch of different queries together like for example we have IDs separate IDs over here and you want to make API calls with respect to each ID so you can use use queries so it all of these features particularly depends on your use case and what you're trying to make so we have bunch of different things over here and I'm sure what you're looking to do with your apis or you know post get request everything you can find inside this Library over here so you can go and explore this documentation so yep that's that is it for this video and if you want me to make a complete project tutorial by using react query just let me know in the comments down below and I will bring in a complete project tutorial on this and if you like this video give this video a huge fat Thumbs Up And subscribe to the channel for more such awesome tutorials
Info
Channel: RoadsideCoder
Views: 19,706
Rating: undefined out of 5
Keywords: tanstack query, react query, tanstack, react query tanstack, react tanstack query, reactjs, react js, react.js, react js query, react query js, reactjs query, tanstack react js query, tanstack javascript, react tutorial, react crash course, learn react, react hooks, react hooks tutorial, frontend development, react developer, react hook, react hooks explained, react-query, react project tutorial, react js tutorial, react query v5, tanstack query v5, react query full tutorial
Id: k1tus-TmqCE
Channel Id: undefined
Length: 39min 41sec (2381 seconds)
Published: Sun Feb 04 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.