Loading
Current section: Form Validation 5 exercises
solution

Form Validation with Client-Side Hydration

Transcript

00:00 Let's open up our edit route and right here. We've got a good place to put the use hydrated hook I figure you can probably write this yourself at some point. We're not here to learn react and so that's why I provided that for you and

00:14 With use hydrated now, basically, I'll explain how this works. We start with a use state of false and so on the server render use hydrated will return false the use effect never runs on the server and so when the Client hydrates, then it will initialize with hydrated as false. The JavaScript hasn't loaded yet

00:35 But then after the hydration is finished it calls the use effect and we trigger a rerender with the hydrated value set to true and so then we know that oh you're hydrated now so we can Return true and you can do whatever you want to with that. So it's a pretty simple hook. We're going to use it right down here for is hydrated value

00:58 from use hydrated and Then we set the no validate prop to the value of is hydrated So we want it to not validate when we're hydrated So with that I can refresh and we can get rid of this and submit and we get the titles required

01:16 But then if the users on a really slow network connection or the JavaScript fails to load for some reason then I can Get the client-side validation that's built into the browser Automatically as well. So we have those options and can give the user a nice user experience there and if that were to fail somehow or

01:38 Sometimes there are there's validation logic that requires the server like username must be unique Then our server-side validation will still catch that but the benefit of doing this is it means that if the users on a really slow Network connection. I don't want to make them have to do a full network request to determine

01:57 Oh, the title is required or or I put a title that was too long or whatever And so let's do all the validation on the client that we can In the case that the users got a really slow network connection now We can also even if we are hydrated and it would be nice

02:16 and to have some client-side validation for some of this stuff to to not waste network traffic and We are going to implement some of that in the future as well So just to review we've got this use hydrated hook that just will return true when the JavaScript on the client has actually run

02:32 and then we use that to set the no validate prop on our form so that we can get the proper browser built-in validation logic for our form