useOptimistic for Optimistic UI in Next.js Server Actions (+ Revalidate)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
one of the coolest new next year X hooks is called use optimistic and it allows us to do the following so if I type here test if I click add now you can see it immediately gets added to the list here I don't have to wait two or three seconds before it's updated in the database and then the latest data is fetched again it immediately adds this to the list and it's optimistic the UI is optimistic because most of the time when we add something to the database it's gonna succeed so we might as well just immediately add it it's going to be a very Snappy UI for the user this is the future of uis let's take a look at how this hook works and also what we want of course is that if something does indeed go wrong so if the database doesn't get properly updated that it's automatically removed again as well we can do both of that today in next year Ash let's take a look at how to do that all right so I have this simple example here we just have a to-do's page and this is a server component so what we can do is we can actually fetch data here I'm using Prisma but doesn't matter works with any database I can fetch data and those are my to-do's so we want to have interactivity with use optimistic so we're going to put the rest of the page in a separate component I call that the to do some component so this component takes those to Do's I'm using typescript here and this is where we have the rest of the page right so we have this form and we have that list so here we actually map over those to Do's that we fetch in This Server component and then we have our form and this form is using a server action right so I have a lot of videos about server actions make sure you check them out add to the server action add to do is this one right so here and when we submit this form the data is going to be submitted here we grab the contents here and here we add it to the database and then we revalidate it meaning it will grab the latest data from the database but basically it's going to execute this line again and so it's going to put past the new to Do's here this component get gets new to do so the props are different and it's going to re-render so it's going to map over the new to-do's right so if I do this now if I now say test two if I press add here it's going to take some time right so here I'm waiting like two or three or even longer right so it took me like five seconds before this test 2 was added to the list here but we can it can be snappier we have the technology these days to immedi leap show test 2. so now we're going to use that use optimistic hook let's see how we can do that so here let's see I have some type definitions don't use interface I have a separate video on that just use type and that's just for the for the prompts here um so now we're going to import that hook and still experimental as of recording this video use optimistic so you're gonna see experimental use optimistic now we can Alias that as simply use optimistic and then we can use that hook here so we can just call that hook it's going to give us two things it's going to give us the optimistic version of the to-do's and so the to-do's that we get as props here those are always coming from the database right because that's what we're fetching here we're fetching these to Do's from the database so that's also that's always what we're getting here the actual to do's and now we're going to have the optimistic version of that and then also a way to add something to that ad optimistic to do okay so these are the two things that we're gonna get and we need to pass in uh two arguments here as well so we need to pass the to-do's here those are going to be the initial to Do's that we get here and then we can add a to-do as soon as we submit this form so I'm going to copy paste it because it looks complicated and and take some time to write out so here the second argument is a function and this function takes in the current state so this is like a reducer pattern and then we can add something here with this add optimistic to do function that's going to be the new to do type to do and what we return here is simply the new optimistic to those right so this looks complicated but let's see how we can use that so now I can copy optimistic to do so here we're mapping over to Do's but that's always coming from the database so this is like the slow way of doing it so now we want to have optimistic to-do's it's going to map over that logic is still the same but the structure of to Do's it's all the same it's just the optimistic version now we're still using the traditional to Do's here here when we invoke that use optimistic so the hook still needs access to that so now we're mapping over optimistic to-do's right so I saved here and you can see it still works the same way so now if I add test 3 if I click add here it won't work so I still have to wait a couple of seconds let's see yeah so it still takes a couple seconds before it gets added here we need to do one more thing we need to add something to the optimistic to do so before we actually invoke the server action as soon as we invoke the server action we have to await that like three seconds so what we can do is we have server actions but you also have client action so here we're gonna we're gonna have we can specify a function you get the form data here from next.js and actually I get a suggestion here from Code Pilot which is actually what we want and this does need to be async and we're going to await This Server action here so let's see what's happening here so this function right now is a client action so this will run on the client here and it will always give you that form data if used the action attribute it's going to give you from data here now we want to grab the content that's the input name right what we pass here and then we want to add something to the optimistic to do it here immediately before we invoke the server action so we do need to add an ID here because I'm using the ID here for key and typically this is created in the database but here it's not added to the database yet so I'm just going to create a random ID and then we need to actually pass the content now the content here can be of type because we're grabbing it from the form it can be of different type so I'm just going to assert that it's going to be a string and then we need to we need to actually invoke the server action and the server action is actually just expecting the form data so we'll just pass the form data there remember this can take three seconds so before we do that we want to add something here so now I'm going to save here and now I'm going to say test number 10 and now let's see what happens if I click add I'm going to click now and you can see it immediately gets added to the list here and so that's really cool very Snappy right so now let's also check the database I'm going to open up Prisma studio and you can see if I look at my database test 10 is also added to the database so now it was immediately added on the UI but also in the database so all of that is still working so if I now refresh the page and it fetches the actual to Do's from the database which we will actually see in test 10 here as this is a very Snappy and almost futuristic UI this is really going to be the future of of UI I think now what happens here in the server action right so here in the server actually when we actually added to do we're optimistic but sometimes you know things can go wrong so how do we make sure that if it goes wrong it also gets removed from the UI here and so by the time we get here it has already been added here to do right so now when we go to the server action here what if something goes wrong here what if I make a typo here right so here we're grabbing the content from form data but what if I make a typo here or something else goes wrong you know millions of things can go wrong here so typically you do want to wrap this in a try catch because there will be an error thrown here if you if something goes wrong here and we want to catch that error otherwise our application is gonna it's gonna crash so we need to attempt to do this and if something goes wrong we want to catch the error I know I have separate videos on how to do proper error handling with the server action so make sure you check out my other videos you can just grab the arrow you can output a toast message here we'll just do something simple we just return an object to the client and we'll just say something went wrong all right so if I save here and now we are making this mistake right so something could go wrong we're catching the error and so now if I do this I do test number 15 let's say if I click add here it immediately gets added here so the add optimistic call is still working but we make a mistake here if I go to the database now it's not going to be inserted in a database so here if I look for test 15 it's not here so here something goes wrong but on the UI it actually shows it here right and if I reload test 15 will not be here right because it's good then it's getting the actual data from the database and where it's not been where it's not present clearly we need to fix this so here we add optimistic to do we want to sort of undo this or refer to this if something goes wrong in this and we go in the catch block here the trick here is to use the revalidate path function so whenever you call this function you will just get the latest data from the database again so what we can do is if it goes wrong we can just call this so before we return I'm going to paste it I'm going to add it here so now what's going to happen is when I submit the form here we're going to add the optimistic to do right so it's going to be shown on the UI here then we're going to run the server action the server action will try to insert that in database but that doesn't work because there's some problem here so we're going to catch the error and then we're going to call revalidate Path which will sort of manually invoke This Server component to run again so the server component will run again we'll grab the latest data from the database where test 15 is not present right because we something goes wrong after test 15 will not be in a database return from the database here so we just got the latest data let's see how this works I'm going to click adds here immediately add it to the UI here and let's see what happens after a couple seconds it gets removed right so it's going to be optimistic to the UI and then if something actually goes wrong we basically say well rerun this component again and grab the latest data from the actual database right where we actually have our source of Truth and test 15 is not present there because it doesn't it didn't actually add that to the database here right so here it's just going to get the actual data the actual to Do's all right now what if we don't make a mistake and it will actually get properly added to the database do we then also want to call revalidate that because it has already been added to the UI so do we need to actually fetch the data from the database again and that's a good question you could make the argument for doing that as well so in both cases you actually just want to revalidate so you can actually also use the finally block here so in both cases it will just fetch the latest data right so if I save here one last try I'm gonna say test 20 I'm gonna press add here immediately gets added to the UI here and now we don't make a mistake here so it should get properly added to the database you can see it stays here so now if I refresh it should be in the database and everything should work as expected so you can see indeed test20 is also added to the database now right so really cool hook we also use it in my react next to S course I highly recommend you check that out if you want to be a professional reactor nextgis developer in any case make sure you've mastered the underlying fundamentals both JavaScript as well as CSS I have courses on them both check out the links in the description thanks for watching and I hope to see you next one bye
Info
Channel: ByteGrad
Views: 10,306
Rating: undefined out of 5
Keywords: next.js, nextjs server actions, react actions
Id: PPOw-sDeoNw
Channel Id: undefined
Length: 9min 28sec (568 seconds)
Published: Tue Jul 25 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.