Learn React State Managment in 2023 | Client Side vs SSR and React Query Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
good morning my gorgeous friends on the internet today I want to discuss a topic that I feel like is very important and it has changed a lot in the past couple of years which is State Management and react and xjs so I know it's quite difficult to sometimes understand the concepts of how SSR works together with client-side rendering and all of that jazz so I want to clarify all of that all the way from just starting simple with you state all the way to rendering content out with server components and then do an optimistic updates on the client I also wanted to say that the full snack react course that I have on my website right now which you can check out and purchase is I remade it pretty much and it's currently being refilmed so that's really exciting uh so if you want to check that out develop.com down in the description click the link and thank you for all your support let's get going hello so let's talk about client-side rendering and kind of just going back in time you know to you know how we used to do things in react and explain that and kind of do my best to show you where we're going because I know once I discovered SSR and uh you know optimistic updates and all this Jazz and I was like what the dude I I don't understand any of this crap so I'll try to show you the to my best ability the difference between um how we used to do things and where we're moving forward with next 13 and API routes and full stack development and all of this Jazz all right so let's talk about how we used to do things with just client-side rendering you know remember the days when you just install create react app uh yeah those days so what we theoretically do back then is just client-side rendering and what that means essentially is um the server would just send back a huge bundle of JavaScript and that bundle of JavaScript would load up in the user's browser right and once that data loads up you'd get to see everything right the benefits of that was that it was once like the JavaScript loaded up it would be super speedy and super fast because it will cache all the components for you so navigate them between stuff and clicking on different pages and go into different routes would be really quick the downside of it was that loading that initial bundle of JavaScript would take ages could take ages theoretically so the initial pains like how long it will actually take for you to see the content pop true uh would be would take quite a bit of time um not only that you wouldn't get the benefits of SSR such as um getting the first initial paint uh loading on the screen really quick with the HTML already loaded which is why people say like oh let's go for SEO because you're actually getting back that from the server and that's very easy for the Google robots to read I guess um okay so let's see how we Implement that right so what you do probably is okay so let me show you kind of what I have um I'm in next here by the way but it doesn't really matter I'll just remove the async here and that's pretty much like uh just a normal react component um and I'm just linking between two pages here because I want to illustrate a couple of things okay so the way we do it is we'd like import you state right and then we'd have our use effect from react cool and now I have some data that I'm gonna fetch you can do like a placeholder data fetch I just made a Wii postgres database here with like a to-do's right so I just have like an ID and a title and that's pretty much it so let's import uh use State and use effect so since this is like a client component I need to add use client here at the top just so it doesn't complain because otherwise it won't work in next but other than that it's pretty much like a simple react component a functional react component okay so how would we get this data well I need to fetch it somehow right so I also need to make a state where I store that data so let's say I have my posts and set posts that's equal to use State and then we'll pass in an empty array cool so this is empty now that's perfectly fine and then you'd use this use effect which pretty much is gonna fetch the data after the component has successfully mounted so it's successfully rendered down this screen it's gonna go out and then it's gonna fetch data so if I do a use effect here like that and I'll just run an arrow function here and I'll pass in an empty array here basically meaning it should only render once when the component has successfully mounted and now here I also want to show you this really quickly in my API they also remade this in next I just want to talk a bit about it it's the same kind of vibe that they're doing now with pages so basically you do a slash so it's in here right the folder the API folder and then you'd make another folder like slash posts and then here you'd add a route TS so I can make another folder in my API routes maybe slash um I don't know like user like get user and in there I can make another route.ts so to actually hit that endpoint you'd need to go to localhost 3000 slash posts right that's it sorry slash API slash posts and look at that if we go here we're gonna get all the data back all right so kind of the same idea make a folder and then just add a route in there and then just hit the folder the URL and then it's gonna work all right and then here I just have uh so this is how it looks now I'll just show you this really quickly because I don't really want to make it about the new route system but you'd export an async function and then you can actually Define what type of method you want to use so if you want to use a get or if you want to use the delete you can separate them now which is really nice and then here I'm just making a Prisma call and I'm just saying hey find all the posts and then return it in this next JS response so return it as a Json and then the same here with the delete and now I've noticed that if you want to get the body as well um I couldn't really find a better way but request.json seems to do it so if you're working with the new API browser just want to clarify this if you want to get the body after you stringify it this is how you can get it with request.json now if there's a better way let me know okay so that's it so in this use effect we pretty much make a call right we'd say const uh let's say get cons get pose I'll call this an async function here like that and here I'm gonna say const response is equal to await Fetch and I'm just gonna hit the Slash API slash post right so I just want to retrieve all the posts from there and then const uh post is equal to weight rest dot Json and that should be that should be fine for me cool and then let's return all the posts okay cool all right so just fetching that data and then I'll just call it here so this use effect works and after all of this oh actually in here what I need to do is after I get that set posts over to the post's response from here all right so just setting the the state up here properly and that should be all good okay so I should pretty much have that data available for me so if I go here and do a post dot map and I'm going to map over each post right and then here I can like return a a div or something with the post ID or postdoc title I should say all right let's see if that works and I refresh and looks like oh it looks like it works cool um you can also add types to this if you want see because it's complaining now what you can do is let's just go here to the top and I can say type of post is equal to and I know it's going to have a number on it and a title on it of string cool so I can just pass this to the response here like that uh and let's hopefully okay looks like it's not assignable okay so actually not here because we're using the state so let's remove it we can add it right here as a post an array of posts like that and that should that should fix our typing error as you can see type post and then if I want to add a key here as well I can do that easily with post.id there we go so author completes now cool okay so that's kind of how we do things right now what's the problem with this now well look if I refresh the page and even if I try to do like a network crap here where I slow it down all right let's go back in time [Music] that's like the dial connection no whatever okay um how'd they do it oh here we go let's drag this up and then we'll do a slow tree g so here's the problem the hard reload and look at that this data is not going to be here for quite a bit of time all depends see nothing there and then you wait and you wait for the JavaScript to load up and then hopefully it'll pop through jeez okay well it's taking time so what we do in this case is we'd have to implement some sort of like spinner and loader to show that hey this is going to be some data coming in here so you'd see people do like posts like if the if there's no pose here or if the post the like length is zero right and then I could like render out like a loading screen or something or like let's just do a H1 here loading all right let's do a refresh I don't even need to do see there we go loading just to show that something is going on and then you get the data back so what was the problem with this well the Spinners suck bro like they're not nice and not only that another problem is this use effect um the problem is that it waits for all the all the whole component to render out and load up and then it starts fetching the data so it's going to be much much slower which is unfortunate and also with use effect it's quite easy to trigger this multiple times unfortunately so if you have a dependency array here that like um I don't know maybe you're updating something else on the page it can trigger a re-render if it has a dependency array maybe you have two in here you can easily create infinite infinite Loops as well and not only that if I navigate over to dashboard and I navigate back home it's going to try to refetch the data again and as you can see it's loading again so it's doing another fetch API call over and why because like the data is here already nothing's changed and not only that we're fetching again so that's kind of the disadvantage of this and not only that well if I want to share this uh state with some place else in my code well then I have to make another fetch call or move or potentially move this out from here and use a state manager all right so that's kind of how we did it and then I'll tell you kind of where we went so if you're sticking with front end then something like react query is going to help you loads because what react query allows you to do is to do a request once um and then cache that data and then you can cache it on all the pages and you can also make optimistic re-renders as well and it also gives you kind of like a is loading function so if we have a look here quickly I'll just show you a 10 stack um not only it allows you to fetch and um where is like a quick start I just want to kind of show it to you really quickly um here we go you pass in the query key that you can name it anyway let's say to do's and then it's going to Cache that for you uh with the function that you're passing through it so if I call get to do so if I call this anywhere else it's gonna get that same cached value for us and then from there you can do whatever you want which is really nice so I'd use react query if you want to stick to the front end because you have that date available through your whole app now so if I want to get this and just pass it somewhere else maybe in my dashboard here let me just get rid of this there we go if I want to pass it to my dashboard here I call that use Query from react query and I'd get that data but I kind of want to go over to next.js side because I feel like it's a bit more beneficial because you can do server side rendering with react query for optimistic data and then basically get the best of both worlds so what's the current situation with next.js well the current situation with next JS is that I can remove this use client and this use effect we don't need to use these anymore remove this remove the use effects so we pretty much get rid of use effect all together and now this is automatically a server component so we can just add async here so that's pretty cool right so what does that mean that means that I can just directly fetch my data here without any issues um I have a picture up here because I saved it uh so what we can do let me close that up um is do a const post here and just fetch it directly from the server now since uh again this is a server component I can just import my Prisma here uh what is it called Prisma from dot dot slash Prisma clients cool so I can just make my call here Prisma dot post I want to get all the posts and let's do a find many cool uh and then I'll just return the posts oops I should have I should have put this in a actually I can I can just do that and that should work fine so that's it one line how cool is that you just do one leg of code you get your posts and you pass them in there and that's it um now you can separate these in in your like own file if you want to like just the fetching uh just so it's not like two places because I have it here too but it's it's one or two lines of code so it's fine so that's it so by default now this is gonna be uh servers I render it so if I go over and to the inspect and let's head over to the network right and we can do a slow 3G again and if I do an empty refresh now you're gonna see the whole data come back without this loading up on the client side it's going to be much quicker and with everything pre-rendered already which is really nice so let's let this load up for a second yeah I don't know why I switched to the slow 3G so let's just put fast 3G but you're still gonna see it so this is so annoying let's just go over to our dashboard and then when we go back you're gonna see that when we head back oh look the data is already there and not only that after the first request it automatically fetches that caches that data for you so if I go here to dashboard and go back it's it should be like instant pretty much because that data is not going to be fetched again so that's pretty cool let's switch back to normal no throttling and then if we go over to dashboards I want to show you this so the first request here when we go back home that's going to be fetched but after that look at that it's it's pretty much cached so that's really awesome so what's the situation with this the only problem with this is when you want to delete something so check this out so if I go here and I have an on click and let's say I want to run a delete function let's just do a console log now console logged and delete cool okay really cool I guess I should run like an arrow function here cool all right so oh well that doesn't work right because this is a you cannot do on clicks you cannot use State you cannot use effect anything you think that you can do on the client um it's not gonna work in a server component so if you add async and if you have and if you don't have used clients at the Top This is not gonna work so what's the solution for this because loads of times you want things to like interact with let's say I want to click on on one of the titles and when I click on it I want to delete it well there's a solution just have your server component at the top so the top level right your page do your fetching for the data here and then make a client component where you have that interactivity so in this case it's right here right so I take this bit of code here and separate it into a new client component so let's go to our app you can make like a components folder here if you want or whatever I'll just I'll just add it here because the way I like to work is I have my page here and then if dashboard has any other components I'll just add them to that folder but in this case this is like a root folder so I'll just do it here let's call it post dot DSX very cool very nice okay so what can I do here well let me have a think about it okay let's go here now and remove this on click that we had here just so our component works fine again cool and then we'll go over to this post that we made and I'm going to add use client to the top nice and then I'm just gonna export a default function of posts like that and here I'm gonna return a div and this div we'll have our posts right cool so let's head over here I'll also just quickly separate this type post here maybe into its own folder as it types it's copy paste this there because I'm going to reuse it so let's call this um post type dot DS there we go so that's pasted there oh this is giving me an error because it's an isolated module can I just do an export yeah export type post perfect so that's good I'm just going to import it here to where we had it just so it doesn't error out where was it where am I using that post oh was it here I think it was here right wait how does it though it's type posts I'm not passing it anywhere maybe it needs to refresh okay cool anyway we'll do that in a bit uh let's head over to our posts and uh whatever I want to do okay yeah so basically I'm passing down the data here now right uh because I can still do that that's perfectly fine so if I import my new client component here and rather than doing that I'm just I'm pretty much going to replace this with posts like that that should be okay and then this is going to complain because well essentially I'm taking in the ID and the title here right yeah like that post ID and post title and then it's going to complain because it's not gonna know the types of it so I'm gonna say post type here uh what did I call this oh yeah post type okay so that should be from and I probably should have done export I think I can still do an export default post type here like that that should work there we go and then I get my post type in and now yeah that that seems to be fine okay cool um what else do we need and then this is gonna complain so let's also import post type from there and then we'll just pass that and this is going to be a ray so passed it as an array so let's see if we get the autocompletes here as well oh yeah something's funny happening here because I'm not passing it down it should just be like that and then here let's see look at that we get also complete so we know it's gonna take in a title and ID so let's pass in the title and as you can see we can do Post Dot and we get the autocomplete there as well Okay cool so let's just pass everything and post ID cool cool okay done and then in here let's just add title in here and then cool I might need to add the key in here actually let's see if it's complaining about any Keys okay no I guess if you're passing the key here it's fine if it complains you can pass it to this diff that looks like it's working okay so look at that we don't have any errors and now you can do this since you have on client there I can do on click and I can just run an arrow function here and say alerts uh I don't know like the title that I'm clicking on right now right so look at that we have the interactivity so what did we learn well we can do server-side rendering and then our interactive components can just use the use client and then here we can do our own clicks and everything and there's a bit of a problem with this um caching system and next I wouldn't say it's a problem sorry I should rephrase this it's really good it's amazing and most of the time that's pretty much all you need where it gets a bit tricky is if you want to share this cache data that I have here with other Pages there's as far as I know there's not a real nice way anyway to really do that you could theoretically copy and paste this over to your dashboard here and fetch it again but as far as I know it's still gonna fetch it once here and then cache it there's no like a key value that you can pass in here to say hey if this ever gets called again make sure you fetch it from the cache and another thing is when you want to delete something um so here let's say I don't want to alert I want to delete right so let's just make let me show you kind of the issue so let's do a delete post right and I'm gonna just set the SQL to an async function and here I'm gonna have like the deleted post right that I can pass through it uh and this is a post type as well so I can just pass in that and here basically I'm gonna say const data equals await Fetch and let's let's go to the API Point again okay so slash API slash post all right but here my method is gonna be a delete all right so I want to send that post in and get rid of it and the body is gonna be a Json dot stringify because I'm passing in an object and I can only pass strings in the body so I need to stringify it turn that whole object into string and pass in this delete post again this delete post is an object if you remember um sorry deleted post I should say be careful because this is the lead post deleted post as you can see this has the title and the ID on here all right so it's an object uh I'll rename this to delete Handler just so it's not as confusing Okay cool so that's it right we are sending uh this delete in and that's gonna hit our route here right then it's gonna hit this it's gonna get the requests uh it's going to get our object from request.json on the body here and I'm just going to do a prismacol where I'm searching for the ID that's on the body ID that I just sent through here basically the one that we click on right I'm going to send that through so here I'm going to do an on click right and what I want to execute is the delete Handler and width basically the deleted post so with the ID and the title like that so that's pretty much I mean that's pretty much perfect I can do consposed await data.json as well to get the data back if I want to see it console log post all right so that's it now let's have a look and see what's going on we go to console and I click on this one look at that I went over to my route it deleted the post and it sent me back the deleted post which is this one cool but look at that I can still see it on the screen now why is that well my data is still cached by next so nothing's really happening here until I refresh that cache so if I refresh the page here now well now it's gone but I mean there's no real clear way of of you know seeing that change happening which is quite annoying so I looked I really tried to look through uh the docs and everything and see kind of what's going on and what they're recommending not a big fan but what they're recommending to do right now again if you have a better way Reach Out um the Imports what the hell did did they use again I think just router from next slash navigation and this might be a used router if I'm not mistaken and make sure it's from navigation and not next router because that doesn't work either and then here I believe they used to do something like this College route equals use router and after everything is done you do router oh my sorry route dot refresh there we go so after everything is done it's going to refresh the page for you and there we go it's gone now but what's the problem with this the problem with this is when I click on this it's gonna take a while until uh the whole back end um you know deletes the post so it might take two seconds it might take five seconds who knows but we'd have to wait for those amounts of seconds until it gets completed and the only then and there the router is going to refresh and fetch the data again from the server and then the cache is going to be gone and this is cached again so that's perfect say it's cached but yeah so what's the solution for this well you can still use react query here but rather than using route refresh we can push in an optimistic update here which essentially means we're still fetching everything on the server but we have that like Speedy client side uh performance here uh I'm gonna warn you the setup is a bit not not too clean not too nice but we'll we'll do it step number one is gonna be to install react query so let's head over to 10 stack and I just want you to install this and run this command all right so click here get started and then we'll head over to installation and make sure you run npmi 10 stack react query cool after we've done that now what we can do is we need a couple files to set this up and I mean it's it's not super fun but we'll do it so first step is and I also wanted to point out that their dogs are a bit funny because it doesn't seem to be working so you have to actually make some changes so let's head over here and then we'll head over to where is the sucker SSR would next all right so if we scroll down here this is what they recommend so the first step is going to be to scroll down all the way to version 13 which is somewhere down here somewhere deep down the hole I think this is the one this might be the one yeah next with here we go cool so the first step is going to be to create a provider jsx here for us so let's head over here um I guess you could do like a util for folder here that has all like the react query stuff so I'll just call this util like that and then in here I'll make a file called provide there's dot jsx I'm not going to make this a TS file it's going to be fine it's just to set up a react query so I just copy and paste over everything from here oops should have copy and pasted the whole thing cool so that's step number one now this is going to error out already because I'm not sure why they did this uh hopefully they can update it um it's importing react but we're never importing react here so we can import either react or just use State and then drop the react here in front I'll just do I'll just do react like that cool so that's the provider and I need to rename this oops where is that did I just delete that providers jsx don't don't tell anyone okay let's copy and paste this and then I'll explain what it does all right so there we go and then let's import uh react right cool okay so we need to create this provider to feed into our application so basically wherever we want our react query and the caching and everything to be available on we need to wrap it with the supervisor all right so we're basically importing query clients and query client provider and here uh I believe we're creating like a new instance of a query client for every user um and then what we do is we take this provider and we wrap it into our layout here this way we still get to keep our layout SSR which is really good so let's import it here import provider providers I should say from dot dot slash or is it dot slash you tell slash providers cool so all we do is we go here and as you can see like they did it we just wrap our children here which represent all of our Pages uh with this provider nice that's step number one done and then there's two ways of of doing this which is with initial data and with hydrate we're going to focus on doing it with hydrate because it's a bit much a bit easier to understand okay so next up what we need to do is create this query client and essentially this query client ensures that uh there's no there's no data shared between any users or any request so just make sure that it creates a Singleton instance of this query client all right so every every user is going to have their own query client so let's do it in this util again so we'll just say get query clients.jsx again this is kind of like once you set it up you just kind of copy paste everything over and then you should be good to go all right now with this code here there's a couple of problems uh it's not gonna work it's gonna error out and the only fix I found for this is to actually set up SSR with um um sorry react query and x13 is to modify their docs I found the open issue on GitHub and what they recommend right now to do is in the get query client change this from react query like they have it here change it to query core all right and then hit save on that again and then here and let's let's make sure everything is good um the provider can stay react query so that's fine so this is perfectly fine but down here they recommend you to import hydrate from react query again which is going to error out again so fix for this is to make another file and then we're going to call um hydrate client let's call it or just even hydrate should be fine let's call this new file hydrate client Dot jsx okay cool here I'm gonna make this a use client and I'm going to import hydrate from react query again this is the thing the error is out so that's why I'm making a new file here and importing it with a use client because we're using this in an SSR see async hydrated post so this is like an SSR component the server component so importing this one works so if we're just making a new file for it to work this might be changed in the future again if they update the docs let me know uh I'm gonna import it as RQ let's see hydrate like that react query hydrate and also get the hydrate props here like that and I'm just gonna make a function called hydrate uh with the props of hydrated props and I'm just going to return this RQ hydrate all right with the props as well I'm just going to spread them here like that cool and then export default hydrate okay so just be aware uh why is this not working oh I guess I made it to TSX Hey Okay cool so again you might not need this in the future if they end up fetching the fixing this bug where you can just import hydrate and that's it but for now you have to make this goddamn file but it's okay all right so those are the three files you need to get up and going okay what do we do now let's close everything up okay so we need to refactor this wee bit so we can keep this that's fine well it's not fine uh what we need to do is just I'll take this uh getting the pose here and I'll just separate it in its own little uh function so I'll just say get the pose and return post cool all right and then what we're going to do is import a couple of things uh I'm gonna get the get query client that we just made get damn it query client from the about Slash I think it's just dot slash util slash get credit clients okay so we're gonna import that as first and now down here I'm gonna say query client equals to get query clients all right so I'm just invoking that and instantiating that for us and I'm gonna say await query clients the prefetch query so this is going to prefetch it on the server for us now and it's going to take in an array of keys now you can name this anything you want just make sure you remember it in this case posts right this is what react query is going to use for its mechanism to to catch the post so if it sees posts and if I do another fetch somewhere else with the posts key here it's gonna go oh that's the same thing so that's perfectly fine and then it's gonna take in for the second argument a query function so in our case well they'll get posts that we have here right and that's pretty much it so that's all you need to really fetch it on the server get the client in and pre-fetch the queries here and then you will have the beehive rated State available here for you so dehydrate query client there we go just like that oh look it imported in as well which is really cool so essentially we're getting back kind of the default uh query from our server and we're going to dehydrate it here and then pass it in here and then hydrate it again so we can use it and update it and modify it and do any other things with it that we want uh so as you can see it says here use dehydrate to obtain the dehydrated state of the prefetch queries from the query cache and then we'll pass in this hydrate um this hydrate basically we wrap around our client uh component with this hydrate okay so you can kind of think of this like as the initial data and then we'll pass in uh that I'll just shut up and I'll do that okay so here now all you need to do is get the hydrate and from the query client now let's see how we export to that oh as a default cool okay so I can just do Imports hydrate from from there all right so I can get rid of this postal link too because react query is going to offer us something much better um now I don't have posts available here unfortunately so we'll just refactor this a little bit let's get rid of that let's get rid of that and I'll just refactor it a bit and just pass and hydrate and we'll do the mapping inside the component so let's just clear that out and this hydrate also takes in the state which is the dehydrated state right so you pass into the dehydrated State and then it gets hydrated now our post is going to need a couple of modifications because we're not taking in anything here anymore like that so let's just clear that out um okay so that's gone which is fine we don't need to use router as well let's get rid of that get rid of that get rid of that just get rid of everything actually just clear this out okay so now what we can do I'll just add a H1 here of posts that's cool um we pre-fetched it here and here we need to do the fetching again at the top so we can just go here and say const data and I have is loading available here as well which is what we can use rather than you know this postal length we have you can just say it's loading now and that's it and once it's loaded it's going to get rid of this H1 all right so there we go so let's save that let's go here where was it to the top uh we'll just call use Query here like that and again this is going to take in uh two things a query key and if you remember we called ours posts so there we go and then the second argument is going to be a query function now mine is really short so I'm not going to bother separating it in another file or anything I can just run an arrow function here and just do a fetch to slash API slash posts and then I can just say and after that dot then return me the rest like rest.json right and that's it I'll just keep it nice and short here so there we go you pass in the query key and whatever you want to fetch again cool um and after that so we're fetching it here again we're gonna say const query client equals to use query client we're going to import this like that now this is not the query client that we have in our util file you only use that when you prefetch datas here in the server side component Okay cool so it looks like we are having errors again and it's that error about that I was talking about with the hydrate uh yeah not working oh I think I found the issue so even dehydrate here needs to be from react core that was a core query core there we go let's hope that that's gonna do it there we go yes finally cool so let's refresh the page um all right we're passing it down here cool so again remember we are past so here and our get post we're passing in the dehydrated state so I'm gonna need to use this data function this data here that we're getting back from the client query here in case the data did change so I'm going to take this data and just render it out down here and kind of the way we did before so I'm going to say data.map and here we have each individual post and for each individual post I'm going to return a div like that and then in here I'll just say I'll have a H1 with the post dot title for example right I hit save and look at that we have it and then I can also pass in the key if I want to so I can do Post dot ID and that should be perfectly fine and again if you want to import the type here and pass and the type you can do that as well I believe you pass it in as a generic here I totally forgot about this but let's hope so and I'll try to pass in an array here let's let's let's hope that won't complain looks like it works it just says that it might be undefined uh let's see do we got post uh yeah okay cool that's better than nothing okay anyway so um we have the data here so what's the advantage that we have with this now well it's going to pre-fetch uh the query here for us on the server and then with the key that we have here but once it reaches to the front end in case the data changed it's going to rehydrate it with the fresh data for us automatically here so that's that's pretty bang and that's pretty cool not only that what we can do now is optimistically delete one of these posts for example and we can do that on the client without worrying in case like if it gets deleted on the server or how long it's going to take it so we're going to do it on the client and then whatever amount it takes for it to get deleted on the server whatever doesn't matter so let me show you what we can do this is this is like really cool um okay so we have our delete Handler uh which I believe we're pretty much Gonna Keep untouched I'm not gonna console log this out anymore here uh just get rid of that um okay so basically what I want to do is on click I want to delete this so with react query you have access to something called mutation and you can import use mutation here so click on that let's import it um and here basically use mutation takes in a mutation function so let's pass in the mutation function in this case it's our delete Handler here right so let's pass in that so that's my delete function and then whatever I want to do whilst it's mutating so I have access to an async function here where I get access to the deleted deleted post for example now where is this coming from well I'm gonna use it here basically when I add an on click I'm going to set the equal to an arrow function that's going to run a mutation so this here right mutation dot mutate and then I can pass in here whatever I want in this case my post right I want to send in the post that gets deleted so this goes from here my post all the way in my mutation here right and uh this delete the post is going to represent that post data here uh cool so now what we're gonna do since we have the deleted post here I'm gonna say wait query client dot cancel queries and I'm going to say the query key I want to cancel is going to be posts like that all right what is that gonna do this essentially is gonna stop any outgoing refetches all right we basically want to stop for a second here and kind of do our own thing you're telling Rick query don't do any refetches I want to have total control about what we're gonna do now so cancel all the activities all the refetches and what I want to do is just get a like a snapshot of my current data so whatever I can see now on my clients so get a snapshot so I can call this like previous posts and I can say query client and to actually fetch the cache data you can do get query data and you just pass in the array like the posts array and that's going to fetch in the cache already just with one line of code and after you do that what you can do is say optimistically update the data so what I want to do is say query client I'm gonna access whatever we have here on the cache and I'm gonna change it I'm going to say set query data I want to change the posts cache and I just want to get the previous posts that we have here and I'm going to filter out and I'm gonna say I have a post here right and I just want to say post.id if that doesn't match the deleted post ID right whatever I'm passing uh here and my mutate so that if it doesn't match with whatever is here and just get rid of it uh this this might throw a Wii error here it's going to say type unknown but it's fine it's still gonna work just fine uh and at the end here I'm just gonna return previous posts sorry yeah previous posts that should be fine cool so at the end I'm still returning this cached data here because I what I want to do essentially is on error or on on like success I want to run a couple more things here uh so let's click on one and look at that it instantly gets removed how cool is that and if I refresh now as you can see that data still stays deleted all right so that's essentially it you get that live really quick um you know re um deletion without waiting for the server um to come back with the deleted data for you but you might be wondering well what if um what if the data did not get deleted on the server I don't want to delete it here on the front end well let me show you the awesome stuff about react query you can do on error here and just say error you have access to your post and the context here and then we can run narrow function and we can say query client so in case it failed set query data I'm going to get the posts right so in case it failed I can have access to the previous post here by saying context dot previous post all right so in case something messes up it's going to revert to it so watch this I'm going to say test that's going to fail obviously so if I want to delete this oh it's gone it's back now well that should work actually oh it doesn't work because unsettled so on settle basically runs at the end of everything right whether it's success or error we can run the code here again so basically unsettled here what I want to do is say query clients that invalidate queries which is basically going to just refresh the cache for you query key and I'll just pass in the posts or sorry it's going to do like a refetch for us so take a look at that I have test here so I click on it look it's back right I cannot delete it it's going to bring back the previous one because we're erroring out on the server so how cool is that you get the instant feedback already here from the server saying oh can I remove that whoops but if everything goes okay fine well then I have my previous posts and then I have that instant deletion which is really cool you also have on success here if you want to quickly see whenever your data finally gets deleted from the server but as you can see it's not going to happen instantly um so if I click here see it took a second for the on success to hit I believe it's on context so you can actually pull in the real data but it took like two seconds but as you can see here instant deletion so that said that's that's everything for me hope you enjoyed this episode and yeah I'll I'll let myself speak at the end of this episode so that's gonna be it for me hope you enjoyed this episode um I would have another follow-up video to make to be fair because there's one specific thing I haven't covered which is Zoo stand and how that Library comes into play and how it can help us in our application so let me know if you want to see that hope you're having a great day I'm loving and living life and I'll see you in the next one peace
Info
Channel: developedbyed
Views: 48,954
Rating: undefined out of 5
Keywords: react, nextjs, state managment, react query, redux, ssr, csr, programming, web development, javascript, csr vs ssr, react client side, react state managment, programming tutorial, fullstack, fullstack development, mern stack, next js 13, prisma, tailwindcss, redux toolkit, zustand
Id: 627vAbdJ9KA
Channel Id: undefined
Length: 55min 17sec (3317 seconds)
Published: Sun Feb 26 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.