Error Handling in Server Actions Next.js (Incl. Toasts!)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
all right how to do error handling in these next year server actions so let's say I have a simple form here I have I've collapsed it just for Simplicity here it's using a server action this is the server action and right now it doesn't contain any mistakes but what if we made a mistake or what if something goes wrong in This Server action how do we output a message to the client or maybe a toast message I suggest to give you an example of the final output of this video what we're going to get here is that if I make a mistake here in the server action and I try to add something here if I now click adds let's see what happens so here I'm getting an error message here toast message on the client because there was a problem on the server and this is what we're going to achieve in this video alright so let me undo this and let's start from a clean slate there so here what we have is an H1 on the page a form and here we're mapping over all the to-do's this is all a server component and in a server component you can fetch data like this and here we have a form the form has this action attribute with a so-called server action right the server action I have defined in this file if I want I could also put it here because it's a server component but for organizational purposes and put it in its own file so in This Server component what we're doing is we're getting data from what we add here and then we try to add it to our database I'm using Prisma here and then I'm revalidating the path all right now typically you do want to wrap this in a try catch because adding something to a database could go wrong so realistically wrap this like this so try we're going to attempt to create a to-do in our database if that goes wrong and prismat throws an error or some errors thrown in the try block we want to catch it here and then we want to output something on the client remember this is all server code this is only running on the server so now we need to send something back here to the client so we can deal with that right so here we're catching the error just to get started let's just try returning a normal JavaScript object here with an error property that will just say something something went wrong let's just try returning this to the client okay so this is all the server so now if something goes wrong and I say oops it's content 2 which doesn't exist so there's going to be an error thrown we're going to catch that error and now we're going to return this JavaScript object to the client so now we come to the client here what we need to do is we just we don't immediately want to invoke the server action we may want to have some some client-side interactivity here so let's remove this because we don't immediately want to invoke the server action we also want to have some client-side code client action so we have server action right only runs on a server but then we can also have an action function here that will run on the client and you can put your server action in the client action so I can actually just call the client action and that will take in that form data of typeform data and in here we can then invoke This Server action the ad to do let's mark that as async and I will say await here before we invoke the server action we need to pass the deformed data to the server action and now before we actually invoke that server action you may want to do other things here like reset the form or do some client-side validation I'll have a separate video on how to do validation make sure you subscribe so we could do that and also what we could do here now is we want to we want to grab the error that we get back from the server so what we can say when we invoke the server action assign the result to this variable right so here if there's an error we're going to return a plain JavaScript object otherwise we actually don't return anything so only if there's an error we will return something here so then we can just check if result and remember sometimes we don't return anything so I'm going to say optional and if there is an error it actually is an error we want to show the error and this is basically the logic the more realistic logic of dealing with these actions here now this one works so here I can now assign this function to the clock to the action attribute here if I save here let's just see what happens if I save here we're going to get an error because now we're trying to add client-side interactivity to something here in a server component this is all still server component so to make that work we need to refactor this to a client component and that's not a big problem that's just the real world so I'm going to create a new component here I will just create that form and I will quickly create that here form and we're just going to put the form in there so I'm gonna remove it from here add the form here and then we want to use that client component here in our server component right so that's Now problem you can put like this and I'm going to import this alright so then we have our client action I'm going to remove it from here and I'm gonna put it here all right so this is now the new page right server component still we can still fetch data map over that here and realistically once you need to add client-side interactivity you're going to refactor something to a client component that's what what we've done now so I can save here need to mark this as a client component so I'm going to put the use client directive at the top and we actually don't need this import and now in our client action here we are invoking This Server action we need to import it here so I'm importing that now all right so now I'm going to save here let's see I'm going to save here as well so let's see what we're getting now okay so now we don't get any errors so everything seems to be working now we can do something we can right we have an error now in our server action so now what we're going to get here is result.ever so we can do something so let's try alerting the results dot error so I'm Gonna Save here and I'm gonna try test to add something to the page and let's see what happens I'm going to get ads and we get a warning an alert something went wrong right so now we are getting the this message from our server action right so here we're sending an objects with the error something went wrong and that's what we're now outputting on the client right so you can combine this client action you can just provide a function here essentially I could Define it in line here as well and actually that may even be more common so I'm going to just in line here right so you can you can pass a function here you're going to get the form data from next.js right here so very handy I don't need to add a separate function here I can mark this as async and now it's inline here so let me put it like this all right all right so we want to Output a toast message we're going to use react hot toast very popular Library so I'm gonna install that react hot toast alright so I've installed it first step is to determine where you want to show that toast on the page so in next year essay you need to go to your layout because typically you do want to put it in your layout file and I'm going to put it right here so I've put it right here in the body and you need to use the toaster component from react hot toast and then you can provide you can specify where to be positioned so I'm doing it in the top right I think that's the most common most people are used to that sometimes it's also bottom right you can also do it in the center but I have said that the toast message should be displayed in the top right so this is just basically the placeholder and now we need to invoke a toast function when we want to actually show that so instead of using alert what we can do is we can import a toast function from react hot toast instead of using alerts we can say toast dot error so now if I save here and there's still an error here right so we still have this issue here where we have a typo we're turning an object here with error so this should still error out so now let's try it again I'm going to click add and now we get a very cool toast message on the client and what we can also do is there is no errors if everything went all right we can show success actually copied already suggested for me toast.success so now if I save here and remove the error from our server action here so if I save here and now we're not really returning anything so we should go into the else block here so I'm going to click I'm going to write test two I'm going to press add here and we see a success message to do edit now if you don't want to use toast messages you can still use a state variable and so you could have some kind of Errors state right just an empty string initially and maybe all the way at the bottom of the form you're gonna display an error if it exists right so just something like this so if there is an error you just display that as a message so then instead of using the toast function you would set the error like this right instead of using toast.success you would simply make it an empty string again I need to input this that's enough I save this if there's an error in our server action I'm going to write test again and now we get this message right so this is a more realistic scenario with the server actions because typically you do want to have client-side interactivity functionalities so you're going to have to refactor things to a client component this is an example of that now one last thing here we're hard coding the error right realistically you want to get the message from the actual error that was that was thrown here so realistically we would do something like error.message now if you try doing this typescript will complain and touchscrew will say errors of type unknown because what we catch here we don't really know what the error is going to be in JavaScript you can throw anything you can throw the number five you can throw a string you can throw an array so this could be the number five right and you cannot say Five Dot message it doesn't exist it doesn't work like that so here this is actually typed as unknown as it's called I have separate videos and they'd highly recommend check out my other typescript videos in the past this was typed as any by default and any means anything goes so now the error is disappears but this is not really the proper way of doing it in typescript right so we don't know what it's going to be unknown is a more precise type and since we don't know we cannot just access that message on here so I have a utility function to extract messages from these errors in my server actions and I'm going to paste it here because I have a separate video on this so this function is called get error message and you just pass in that error here and it will extract a message as a string for you so instead we're going to use that function here I'll explain it in a second so we just call this function we just passed that error right I don't need to type a noun here that's actually the default these days error and noun we pass the error to get error message this function takes in this error it's going to be of type unknown and it returns a string right so here we specify the message going to be a string and first maybe they they actually threw an error that was actually created with that error class that we have in in JavaScript right so maybe an error was actually thrown like this new error so then we go in this first if block and you can actually just use that message right so that's there's actually a message property on that error object no problem you can use it maybe they threw a normal JavaScript object and maybe there was also a message in there right so maybe they through you can throw just an object literal with a message like that not an instance of the error class but just an object literal you go into this if block the message property could technically be a number right so the value for that message could be a number or something else we want to cast that to a string or maybe they actually threw an actual string so we can just use that as the message and otherwise we have some defaults here something went wrong and so this function will always give you some message and that's what we're going to return to the client here so now if I save this we still have this typo here and now I try again test five I'm going to press add and now you can see we get a more specific error message if you want to complete walkthrough of how to properly extract an error message here with typescript check out my other videos now to make sure you've mastered the fundamentals in my reacting next yes course we also talk about typescripts specifically in the context of next.js and react so check out my course on that also make sure you've mastered JavaScript itself it makes things much easier and of course also CSS of courses on them both check out links in description thanks for watching and I hope to see the next one bye
Info
Channel: ByteGrad
Views: 14,737
Rating: undefined out of 5
Keywords: next.js, server actions, nextjs server actions, react actions
Id: nsMzWA6_3RA
Channel Id: undefined
Length: 10min 30sec (630 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.