TanStack React Query v5 Full CRUD Tutorial in 40 Minutes

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
I'm going to show you how to build a react application with create update delete and fetching of data from the server side we will be using the 10 stack query version five version five is the latest version at the time of this recording we will also be using react router or router depending on which side of the pond you're from to navigate between Pages we are of course using vit as the dev server and file bundler in our development environment and we will be using Json server to simulate the backend I'm going to demonstrate the completed app side by side with the simulated database or database depending on what side of the pond you're from and I will show you how to set all of this up so in this world all songs are written and performed by Taylor Swift hence the Taylor Swift apocalypse so I've seed the database with uh three songs and albums so right off the bat is doing a successful fetching of the data let's take a look at the network tab okay it's going out and fetching our songs with a 200 200 this icon here is the 10stack requery developer tool and I'm going to show you how to install and set this up as well it's wonderful so let's demon demonstrate the post request let's do a test song a test album okay doing a post request you can see there let's do a uh a view of a let's go fetch a single song So if I click on that hyperlink it'll take me to a single song here you can see the song ID and this ID is generated by a plugin npm Plugin or npm package call uu ID which you're very familiar with using the react router to go back to the main View and then if I wish to edit edit it or update it okay updated submit as you can see there it's been updated so that's our put request now let's do delete it's deleted and it's fetching the uh data from database again so who is my intended audience for this video I would love to say everyone but as you know I cannot make everybody happy all the time ideally you have familiarity with JavaScript of course the react library and the react router Library which is uh pretty important in this app you just need to know the basic of how react router works you do not need to know uh 10 stack react query I will help you with that so if you're trying to update from version three or version four to version five I will help you with that if you are absolutely brand new to react um query and you've been using use effect all this time I will help you with that I created a GitHub starter Branch for this tutorial with the barebones photo structure and the completed backend I also have the completed version of the app in the main branch just give you an idea how popular R query is in the last seven days there have been 2.5 million downloads and of course like I said before we're up to version 5 live now but the the last version the last sub version of version 4 had over 700,000 downloads in one week okay so there's going to be a lot of people looking to upgrade to version five here soon if you were to pull down my starter app from GitHub for this tutorial make sure you run npm install to install all of the npm packages let me explain the simulated backend I'm using Json server as I mentioned before and I've created a db. Json file to simulate the database and here I have some C data with three songs now my Json server it's working with another npm package called concurrently so what concurrently allows me to do is to run the Json server uh simulated database along with the V Dev server so the command server n if you run npm run server in the terminal it will run the V def server along with the Json server okay so now I have the front end up and running along with the back end and if you look at the database script here I'm watching for changes on the um on the um the database itself if there's any changes it'll update by itself and you can go to Port 3 Local Host Port 3000 to look at the data and of course you will have to go to this endpoint here which is called songs the songs endpoint if you notice here on line 22 I've also installed the eslint um query plug-in for TSTC and of course the dev tools I'll show you how to set up in a bit but in terms of the eslin for 10stack in the ESL RC file you notice I've changed the format tojson I like this format because you know as developers we use that format according to documentation you need to add this line to the extends array okay if you are using prettier make sure that prettier is always the last element inside of this extend array okay and one more thing I want to uh note well two more things actually axios uh I'm using axios axios is superior to Native JavaScript fetch it has better error handling among other things as well as other options that native fetch don't have including an Interceptor okay and this p package axio is industry standard it gets about 3 million downloads every week for on npm and then of course uh the uh the the router or the router um because we're switching P we're switching view so we can need that router in there so let's take a look at the frontend folder structure for this app but before we do that if you're not a subscriber to my Channel please consider subscribing it's completely free and it'll help me grow the channel thank you so much okay so the the thing that I want to note is I have a directory here called pages and the files in the pages folder have the jsx extension which means they component yes they're component but they're react router components or router components so they're not reusable they're they're components for the react router like I said so therefore they're not reusable so it will make better sense to have it outside of the component directory uh which is in following the pattern that was established by next s and then um I have a custom hook uh directory now if even if you're not using react query or t query it's a better practice to separate out or exract out your use effect just for sanity purposes so that your component don't get too bloated and for testing purposes later on and then I have a Services directory where I have a songs. API file to make interaction with the backend so let's start with interaction with the backend API in the services directory in the songs api.js file I have just very basic fetching stuff fetching all the songs fetching a song and pass it into the ID very standard JavaScript nothing groundbreaking here you want to pause the video to type that down or you can just copy and paste from my repo in the in in the main branch update delete very standard stuff okay now I did mention that you should be using axios okay if your company prefer to do things the hard way feel free to use fetch but if you prefer to do things the easy way using axios go ahead and copy my code here here okay I've I'm using both Fetch and axial so that uh you have a reference in case you want to do things the hard way and the unsafe way but I'm leaving this in here so that you can have options let's go to main. jsx file now we are starting to get into the heart of 10stack react query so aside from the normal react importation I have the standard um browser router pattern here where I am importing the browser router module from react router and then wrapping my app with it so that I can use it to to rout to different views all right but from 10stack R query I want the query client query client provider and of course the dev tools and then I want to create a cono cery client constant and invoke the query client Constructor like this the query client Constructor will take as an option this default options object here now my goal for this video isn't to go through every single minutia of the 10stack cury library I will refer you to do to the documentation for that my goal is to get you up and running quickly if you're upgrading from version four to version five or even from version three to version five um or if you're brand new to R cury to wet your appetite and get you up and running with full crud operations quickly if I go through every single minutia that video will will last like an hour and a half the first component that I want to work on is the song form component which is this part of the application it has a uh two input Fields a song and an album so in code this is what the song form component looks like it takes two props onsubmit initial value the ini initial value is of course a song and album and that is going to be to empty string if it's not if there's nothing else coming from the from the API and then I have a dynamic function to create two input dynamically well in this case to input and that is the song and out album okay and then I have this handle change input function that will be fired when the input gets changed and of course I have a handle submit um function that will handle form submit just very standard um react stuff and then this component will be used in the add song component and the edit song component in for the react router now let's open up add song component and work on our first mutation together so let's import the use mutation and the use Query client module from tack we're going to need uid for this and we're going to import create song from the API interaction because we will be using this function and of course we are going to use the uh for Lao term the the static component that we created previously uh and we will pass data down to it intense stack query anytime that we mutate data we need to use the Ed query client Hook from uh TC okay and the common pattern is to declare a constant called query client and then we're going to use the query client inside of a function to mutate so I'm going to declare a function called create s mutation for now it's just a shell function and uh this function will use the another hook called use mutation which I imported up here and then inside of used mutation the typical pattern is that we're can have a mutation function okay now you can write an async function here but if you recall in our songs API we already have a create song here you can see I'm using fetch which is comined out and I'm using axios which I prefer okay so and it's an asnc function right so you can either declare that a separate file or you can declare it here the cleaner pattern is to declare it in separate file so create song will be our mutation function and then one of the other option is on success now there are as you can see here with my intellisense it gives me multiple option right but the typical uh pattern is to use on success and then we pass in a a callback function so our query client constant is storing the used query client Hook from tan stack and so inside of the unsuccess Callback function we will use a function from this hook invalidate queries like so so let me explain the concept of this invalidate queries function that's also an invalidate query singular function as well in this case I'm using the plural form so tanack fetch and caches data for us now if the data uh I'm sorry excuse me if the data in our app changes over time then it's become it becomes stale and invalid so therefore tanac will go out and fetch new data for us and cash it if necessary it and it it it it does that in reaction to data changes and state changes in our application now if we need fine grain control over the stealth time we can set the Stell time otherwise uh tat query will manage that for us now if you look at the signature of this function it takes the uh query key and then an array data structure and then some options right so the query key has to be in this form here in that form that verbiage and then the value for this key will be in the shape of an array data structure with a serializable string the reason why you need an array is because you can pass multiple uh key in here multiple values in here so what the heck is security key in in our case is called songs well think of it as a as a constant uh for the data in our app okay and it's used react query or 10stack react query is using that constant as a reference to our data so that it can make updates and changes and cach it if necessary so that's pretty much it as to uh what a CER key is let's go ahead and conso out success if we um are able to successfully create new songs and I need another function in here and let me just paste it in because we're getting low on time and I I'll explain what it is so we need a way to uh fire off this function right and so that's going to be our event handler and as you if you recall the song form component one of it props is this onsubmit function right and so I'm creating this Handler passing into the song okay and then I'm gonna call this mutation function here uh and it has a mutate function on this hook and it pass in The UU ID which I'm creating I'm creating that long ID for each particular song and and then I'm spreading out the song basic react stuff the only thing different here is this function call here for the mutation so just a quick note this mutation this create song mutation function here this can be abstracted out into a custom hook for example it could be a custom hook inside of the mutation file and then import it to keep this component clean I'll demonstrate it later on so we're past the 20 minute Mark so I'll be flying through this tutorial for the rest of the time the next component I want to work on next is a react router component excuse me router component which you can access by clicking on the individual songs and then it'll take you to a song one song singular and you need the ID for that you can see here you pass in the ID in the prams that's why it lives in the pages directory and why and that's why I need the uh react router in the song component I went ahead and set up the scaffolding for react router and I've imported the appropriate modules to use and I declare uh I set up a navigation constant I put out the the ID from used prams and in the jsx I set up the navigation and uh the song now this is this is forthcoming this data H song this is will be coming from uh 10 10 stack fetching so let's paste in the scaffolding code here so up here I've imported the used query Hook from tanst and from this hook I can destructure out it's pending it's Error data and error now if I've have alas uh data with hit song to more easier make it easier to reason about um now if you're coming from an older version of T stack query this used to be called is loading now it's called it's pending so the pattern for used query Hook is similar to use Ed mutation I still need a uh I still need to pass in an object right uh I still need a qu query key and the value for the query key still needs to be in the form of an array I passed in the songs constant so that uh T can keep track of the data in the app and I need to pass in the ID which I extrapolated up here because I'm pulling out a single song with an ID right so that's information that's uh information that 10stack needs to keep track of and I need a query function I'm going to pass in a callback here fetch songs which we declare in the songs API and I need to pass in the ID up here okay and so now I have access to hit song the songs in and hit song If You're a stute you know you know why I call this hit song so that we don't have a song song situation right let's work on the editing feature next where you edit a single song it's very similar to the song component that we worked on recently you click on the edit button it'll take you it'll fetch a single song with an ID and then from here in the two fields we can go we can edit this submit and you can see the change is there conceptually what we are doing in edit song edit a single song is very similar to uh what we did previously in song in that we are still bringing out a single song with an ID so therefore we still need to uh use the uh the query the use Query and then we still need all of the react router stuff but what's what's different here is that we are going to update the song and the and or the album so therefore we need to import in the use mutation Hook from the library and we need to pull in the function update song function from the songs API and so let me just paste in the skeleton function uh anytime that we again anytime that we uh mutate something we need to bring in use Query client and we store that that hook in this constant here create client so inside of this use mutation function it takes an object and inside the object we need a mutation function and that mutation function is just that update song that we declare uh in the songs API again we can if we wanted to we can abstract out uh these queries and mutation into its own custom hook and I'll demonstrate that a little bit later and then we're going to need an on callback function and then I've already went over the invalidate queries concept and we're going to be using sort of the the same concept here so we're going to call query client we're going to use the invalidate queries function on the hook and we're going to pass in the the query key of songs that we're going to m mate in the form of an array and then after and once that's done we're going to navigate to the uh root directory okay and then the all the um the error checking and it's it's pening state changes we need to communicate that if to the end user if uh they're on slow Wi-Fi what we need now another function to fire off this updated uh song mutation function in the event handler okay so let's go ahead and get that in there it's going to be very simple we're can uh the hand the submit Handler will take it an updated song then we're going to fire up the function called mutate on it which is the functions provided inside the hook pass it the ID of course right that's how we extrapolated the ID up here and then spread out the updated song okay and that's uh pretty much it for the logic now we just need to return some jsx and the jsx that we're going to be returning is the um the static component that we created earlier song form okay um and then again the song form takes in one of the props it takes in is on submit Handler and then we pass in the submit Handler and that's pretty much it for this component before we work on our final react router component let's work on creating custom hook for mutations and queries I've been teasing that for a while so let's go ahead and take care of that so as you can see here I've created a custom hook directory in there I have a mutation. JS file and a queries file to separate out to separate out the mutations from the queries and so in the final mutations I imported the used mutation Hook and the use Query client hooks like just like we did before from the library and I need the delete function from the songs AP just as a reminder this is what that function looks like and then I need to um export a function called use delete song which is name of for custom hook and just like before I need to store this use Query client hook inside of the query client constant and then we are going to return use mutation hook that we imported up on top is a function call and then we pass in an object as this first argument we declare a mutation function which as you guess it will would be delete song and then we need an unsuccess callback and then inside of the on success callback just like we did before we're going to call create client and we're going to call the invalidate queries function we know what the signature is already it will be query key which again is songs and then if it successfully deleted a song then we will console lock song deleted with a party emoji I I tried to find Taylor Swift Emoji but couldn't find one so and then let's go to the uh the query one uh this is going to be mindly boring for you so I'll just go ahead and paste it in so that we can save some time because we done this enough times already the same fun the same pattern as before if you noticed earlier I had a typo in the file name here it's supposed to be song list not song list I fixed it and then I also done the scaffolding for this file I bought in the use navigate hook for uh react router and then I brought in this child component so that we can add songs and album uh for this component because there's a component again that we can do all things and I brought in the two um custom hook for mutation and queries that we just built and so let's go ahead and uh immediately bring in our two um custom hooks for react query and so for the query but in the use of suspect is pending is error data which I've abstracted out to songs to make a little bit more sense and then of course to error and then let's go ahead and bring in the used delete song and we will assign it to a constant called delete s mutation and then we can uh use this constant in an event handler later okay so now that we brought in those two custom hooks let's go ahead and handle error and latency should that occur okay just a very simple message and let's now uh create a function to use the delete song mutation it's very just very straight up reacts JavaScript stuff the only difference here is that we are using the delete s mutation we're calling the mutate function in the hook okay and then we passing the ID obviously we need to know the ID to delete the correct song right so now all we need to do in the jsx is to map through songs which is coming back from the API and then render it out so the first thing we're going to do in the jsx is to add the add song component and let me just remind you what that is it is dis part right here okay and then uh we are going to run a basic JavaScript mapping function to get out all of the songs and album and these functionality buttons all right so uh it's just a basic appap function through the API data so it's not really that complicated at all and um let me see here and this event handle it here this handle delete it's going to be invoked here right it's going to be invoked here on on click when they when they press on the delete button here okay now of course you have your uh your edit button here and then um the the router here is when they click on the header like the the name of the song to go to the individual song view okay so that's the end of our components now the app jsx it's still empty so we need to fix that we need to add code to that so what we need here is of course um the react router because we're going to from here is where we declare all of our routes um and then in terms of the local files we need the components that has a relationship is attached to react router okay so we need to import those react rotor components as local files okay now um now just uh if you're familiar with if you're familiar with uh react router and how that works um this is a piece of cake okay the the base R of course is song list which I just show you and then um for the individual songs we go we go to the route with the ID and of course to edit the song we go to the um to the song with the ID and of course the the edit route very basic uh routing if you need help with uh react rter let me know in the comments I I'll try my best to help you every version of react rter it is breaking change it's like a new it's like a new library every for every version but uh but every version is getting better and better so there's breaking changes because they keep on improving the product the same thing with with with 10stack query the reason why there's so many changes is because they're they're making they're actually making it better and and when they make it better wholesale that's going to be breaking apis so just something we have to deal with as developers okay so that's it let's go do some testing okay so I got the app running um by running the command mpm run server which once again is to run both the front end and the backend let's take a look at our database so we have our seed data there as you can see in the UI as well as in the database uh let's make sure this link works right here's album by the way this color I know from a very reliable source this is Taylor S favorite color anyhow uh let's add a new song and album let's go let's just say test test album okay okay there's our data okay great edit one one one one one submit there's a result okay uh let's okay delete gone okay uh let's also make sure that this yeah okay so this wonderful react uh uh query tool I I keep on saying react query it's actually called 10 stack react query but I'm so used to calling it react query that slip with the tongue spend some time uh reading up on this tool it's really good it's really wonderful um let me see here okay so this piece of documentation here if you're updating just an FY their documentation is extensive and that's a double edge s sword that's why I'm making this video because going through here is like watching paint dry but um so the red functions are o functions and the green ones are what you're supposed to replace them with okay also have a look at the guide so this is your friend but like I said before it's uh that's a lot there okay uh but it's it's a great it's it's a great piece of it's a great piece of kit all right my friends thank you for watching thank you for uh bearing with me if you like this please consider subscribing uh you know people that needs help with react query refer them to my video see you next time
Info
Channel: Huy Nguyen USA
Views: 3,257
Rating: undefined out of 5
Keywords: Computer Science, Software Engineering, TanStack Query v5 Tutorial, ReactJS Tutorial, React Query Tutorial
Id: 1UJ2MdT36o4
Channel Id: undefined
Length: 40min 11sec (2411 seconds)
Published: Mon Jan 22 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.