Part 2 - Setting up React + Typescript + Hooks - Material UI, Easy Peasy, React Hook Form

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hello friends welcome to coding garden with CJ well the drop game is very much stunning welcome to the show this will be a continuation of the stream that I started this morning where we are setting up a react app with lots of different things we've got typescript with react app we've got material UI we've got react router got es Linton prettier setup we're using easy-peasy for our state management and we're also gonna use react hook form which we haven't gotten to yet we'll do that in the stream and this is a library for managing forms using hooks it's pretty sweet we're gonna talk about that so hello everyone welcome hello Vishnu hello Chris who is ready for easy peasy it's gonna be a good time hello welcome back from Hedra chubby shady is asking why easy peasy can't you just use context we'll talk about that you technically could like you don't have to use really any of these libraries you could write it all from scratch yourself one of the things that I like about easy peasy that it adds on top of just like creating a context at the top level and then using context and a lower component is the way that you update state and they also have thunks built in so ways of managing asynchronous actions which you would essentially just have to use create your own global hook that uses a context and also has internal state but then also uses effects if it wants to do async things but this handles all of that so that's why if you have any specific things you see that are potentially like easier with context please let me know because I really haven't used it that much but as far as I know that's why we're doing doing what we're doing doing what we're doing hello Jorge welcome hello it's Han welcome hello Zachary hello Steven hello Ben hello motivation yep we're gonna keep on doing it and hello Sergey who says just passing by to say hello on vacation with my family seeya and good coding oh that's awesome we'll enjoy your vacation thanks for sayin hello Mejia says I can't follow how long my code folder is on another computer which I don't have in this moment this is ok I'll open up a live share just like I did earlier so you can at least look at the code that I have here and I've already pushed it to github so you can check there as well so that's okay let's copy this so if you would like to join my coding session you can go to this link here open it up in vs code and you'll be able to see all the code as I type it and such and hello by polar bear I have used reactant before easy peasy is more than what reactant provides reactant is sweet and I've used it on stream before if you look at the streams where we were working on what's it called snap garden we were using reactant and it has a pretty cool hook in it called use global so you can create global State but again ezpz is like I feel like a step beyond that and you'll see you'll see why motivation has a question do I have any JavaScript libraries that generate subtitles from a video I haven't heard anybody I could do some searching around but I haven't heard of any but alright let's get into it so this is the app we have so far it's super basic because we did a whole lot of setup we got pretty hung up on our es lint and prettier plus typescript plus Airbnb config all in one getting that going that took us a while but we have our app going we have a basic navbar up here using material UI we have our home page which right now lists nothing and we have our about page which is that so this is using the router and one thing I'll show really quick is actually getting some data showing some data on the app so our guestbook so this is our interface our guestbook implementation has no values in the entries array but if we create a guestbook entry c.j con yeah that's what it's called is hello world and the submitted I think is the property is a date like so so now my initial state of my application has this object in there and so our home component is reading from that store to get that array of values great I think what we'll do next is we will set up some actions so that way we can add new entries into this array I think we'll do it all locally first to show how creating custom actions works and how you can modify the state and then once we get all of that working we can hook it up to a back end and actually like make some API requests so that's the plan and hello J get at you who says just came over to say hi got to go now but hopefully we'll be done with my study and come back awesome enjoy your studying thanks for dropping by Chris says easy peasy would not be possible without the existence of UX it looks very similar and you can look on the ezpz website if you look at bread recipes introduction prior art so if you look at the prior art page on easy peasy they show you other libraries that do similar things that came before this library and what their potential inspiration for this library was but definitely things like view X and in the react world they use mob X which is really just a ripoff of view X or in like view the way view handles things so that's a thing but okay where do we go from here an evil Pisces is back from work welcome double stream yeah we got it we have finished the app restarted earlier because we did not finish and hello Andrew welcome to the show so I think we'll start there I think we haven't we might actually before we get start talking about the store and stuff like that let's just get a basic form on the page for submitting a new guest book entry I think I think that's the way to go so here's what I do I want to create a new component and [Music] I don't like typescript I talked about it very much this morning but it's useful and I'm showing you how I use it in react so I need to create a component I'm going to create like a guestbook entry form component we could create just the file in the home directory here we could create it in the components directory I mean really a pin home should be at a top level I don't know I should give more thought to the the structure of this but for now actually I'm going to I'm gonna create a folder in components called guest book entry form and so we're gonna create a form where the user can input their guest book entry Andrew was in school and I stream I see and Colonel panic hello is there way to see prior videos in this series to see the set up of where you are now I just streamed it this morning so if you look on my channel and look at past live streams it's the stream from this morning but yeah and all of all of my live streams are archived so you can really just look at my videos page and that's all of my live streams okay so we're gonna in create an index TSX this is going to be our guestbook entry form component we're going to import react from react we're gonna create a guest book entry form function this is gonna be like a nice little functional component just gonna write now we're gonna return just like an H 2 that says entry form and then we'll export it defaults so we'll say export default guestbook entry form and we need to type this thing so I'm gonna say this function is of type react FC which is a functional component so there's your typescript and now we need a form but let's add this form to the home page so we have this component why is this complaining I hate it I hate it why are we getting that error um I think it doesn't like whenever whenever I create new files like the the linter and typescript have a really hard time figuring things out I'm gonna leave that there for now and now in my home component which is the component that's showing all of the entries I'm going to show the form right at the top so let's import that form component import guestbook entry form from go up one directory and grab the guestbook entry form like so and then we will use the guestbook entry form right there so we should say hello we should see hello for entry form right at the top we do awesome I could do it with view but the thing is there isn't really a comparison because with view everything is just built in you have your router by default it sets up your linter by default it has view acts state management that gets set up by default basically the two hours that we spent this morning would be done in a matter of five minutes by generating a new application but I can definitely build a similar app with you if that's what you mean we're not using redux we're using this thing called ezpz which is like a replacement for redux yeah thank you me Hedra kernel says this seems like a super chillin kind community you wish decoding and happy to be here well thanks for being here yeah we yeah we try to welcome the the newbies to the code well we welcome them to the show if you're a newbie to code alright so the for the forum is showing up that's a good thing let's actually get the some components from material UI to actually show the form and such let's see what's going on here why is this complaining unexpected block statements surrounding arrow body that's okay expect an invitation oh my goodness oh my god what if we just add a console log right here failed to apply fixes to the document [Music] let me see the output from yes lint why why must this happen I don't know I just want to write code keep breaking you know what it might be the it might be the live session here's what we do I'm gonna close the live share session and I'm going to reload the window and if we don't run into issues then I'm gonna leave the live share session closed if we do run into issues I'm gonna open it because obviously we're having issues anyways so let's give it a second see what's gonna complain let's see you have you as cool one love says I've been coding for 15 years and I'm still learning we didn't have react back then it was cpanel PHP in my zoo cool yeah I remember those days I mean they still it's still technically around in hello Daniel garden as you can see the document is now fine Manoj mentioned right-click in for my document yeah I had already done that so right now when I do yes lint fix all audible fixable problems that actually ties in with prettier and formats the document yeah so and then prettier gets rid of my extra yeah but the document was fine the linter was just broken so I'm gonna leave the live shirt closed but yet never stopped learning you gotta just keep on learning okay so let's go to the material UI Docs and we will get some components to add a form material UI this thing a multi-part series the thing is it should just work right I shouldn't be struggling this much okay so we need some components we're gonna need a text field we'll do a standard material design text field that just looks like this so yeah let's do it so instead this h2 I'm gonna have a form not a from a form I'm gonna add no validate to it because we're gonna handle all of the validations with JavaScript and use in conjunction with react hook form we need a text field and my autocomplete know my book complete isn't automatically importing it that's fine we can do it manually I'll say import text field from at material UI Core slash text field and then inside of here we'll have a text field say the label is going to be name the name is going to be name and let's want this thing should look good what am I gonna code in angular in a few weeks I don't know okay so we have the form one thing I want to do is the container here that's like below the navbar I want to add a little bit of padding on it I think they might have like a container class yeah look let's see so fluid container with is bounded by a max width property value that's cool so let's do this in our app component and hello assets Park welcome but in our app component right here where we have the routing we're wrapping it in a div instead I'm gonna use a container and we do want to auto import that from material UI and actually what we'll do is instead of destructuring it will import that one specific component so you can read about it more in the material UI docs but if you import that one individual component directly your bundle size will be smaller because if you D structure it then technically you're bringing in the entire core so we just want that one container component and then we can say max width probably medium what are our options SM if you've heard design for a fixed set of sizes instead of trying to accommodate fully fluid I guess we'll just do max with small and see what happens so right there max with small see what we get nice and it that's like a maximum size I'm okay with that it's totally fine with me and now for our form let's add a few styles so I'm going to add my styles dot TS we're gonna import make styles from material UI core slash styles and then we're going to export default you invoke make styles you pass in an object and then this object can have classes on them with certain properties so I am just going to create a class called like form container and I'll say like margin one rim so it'll have some spacing around it and then now I want to use these styles in my guestbook entry form component so right here I'm going to import styles or actually it's used styles from that Styles file and then in my component I can use this hook to create my classes so I'll say classes equals use styles this turns that object that we were just looking at into a set of CSS class classes so we're gonna have this form container class and so then we can actually use it and I'm going to put it on the form so I'm gonna say form class name equals classes dot form container and that should give it a little bit of margin very good alright I want these text fields to be full width so if we look at input or inputs textfield I think there's a way to make it full width sizes small normal full full widths how do we do it you literally put the full width prop on it so we're gonna do that so on this text field I'm gonna say full width and there we go so someone can enter their name like Bob and then we'll add a field for their entry and a submit button let's catch up [Music] reiax can build for all the major platforms so can other things I don't know what brings work I think eventually if we can just think of an app and it can appear that's the ideal situation like eventually we won't need to go through all this setup to build things and thanks for the follow grin grenade or even welcome to the show yeah so I'm not using style component so if you look at material UI you can look at their styling system and it uses CSS in j/s which is this thing which I actually prefer and I prefer it because it has really good integration with typescript so you saw a second ago whenever I said use styles and I said classes dot typescript automatically knows what all what what what classes are available to me based on that I'm sure you can do that a similar thing with styled components I just I like the way this works and then at the end of the day these actually it turned into style sheets so these aren't like inline styles or anything like that and technically you can use this syntax if you do want to use like back ticks with CSS inside of it I don't like that though because then the the style code can adhere to the same style rules as my JavaScript so but material UI is using that library under the hood so if you look at the basics they talk about how to define your style sheets but at the end of the day they're using that library how do I know something looks right in the browser um I think I'm at a hundred percent oh no I'm not okay usually I'm at a hundred percent it looks fine that looks fine at a hundred percent I think technically our container class that we put in app which is right here what if we set this to large hey that was a good guess it worked and it should Auto still Auto resized cool I like that oh no let's let's go medium medium is that a possibility nice okay and thanks for the follow Doug Heisenberg hello Joe mama good morning Doug hello doc what's up um client telephone says might as well start learning quantum computing frameworks now yeah you should right now do it all all the things we're doing right now will just be totally pointless in a few years but that's okay what was I doing I don't know but we need another input so we have our name we want an area where the user can input content so I'm just gonna add another text field and I believe there's like a multi-line property but the label for this is going to be content actually let's capitalize it content and the name is named with a capital N and the name of this text field is content but is there a multi yeah there's a multi-line property so we can say that I mean you can also specify the number of rows so let's give the user three rows there we go so we have the name we have the content I want my my text fields to have a little space between them because you can see that like the label but like touches the one right above it so let's give a little bit of bottom and top margin to all of my inputs so if we look at the styles we can see the classes that are applied to each and like each individual text input so you can see we have our form and then you can see that each of the text fields has this UI text field root class and so I'll show you how we can like do Ness did nested selectors in that JSS so I'm going to nested select any mu I text field root element that is inside of the form and so let's do that in our style file so the way we do that is say inside of the form container and any nested elements with the class new UI text field root I want those to have a margin top and bottom of I don't know one rim and left and right of 0 like so and so this will select inside of the form the element that has the class me my text field root so now we get a little bit of margin in between them and you can see that if I select that element this is the style that got generated by that CSS and j/s that thing there do I think there won't be a need for web developers any time any more than and and what what timeline do you think that would be I'm just I'm sort of joking right now eventually yeah like no question how long that's gonna take I have no idea humans are not good at estimating I'm not good at estimating and hello and me like 2d welcome to the show man Manoj is asking how to get a good command over CSS personally I just just practice but there are some good resources out there and also trying to adhere to some sort of CSS pattern like BEM block element modifier that can help you become a better CSS ER but yeah I don't have any any resources offhand for that cool so we got this form that's great you know what I think I'm gonna go with the outlined look I do like the material design look but you can also do is it variant yeah variant outlined let's see what this looks like I kind of like that so it's nice and outlined yeah I'm a fan of this very good J says I randomly stumbled onto your connects tutorial where you walk through and create a credit PA you have a second part to that where you include off in authorization sort of it's not it's not exactly in line because we're not putting it on the same API but if you look at my channel just search for coding garden off there's a playlist on adding off to an express app and you could use the same app that you built in the credit API one there's also some videos on my channel called off from scratch and that that video series is for like complete and total noobs and we build an API with auth in it from scratch so you can take a look at that - is it still worth it to become a web developer yeah I mean you got another good 10 years or more left a piece of what we're doing here I don't know I don't know I have no idea don't listen to me I have no idea typescript is okay trying to yeah that's that's a good point to try emulating an existing website to practice the SS it's always a fun exercise like a while back I tried to emulate the video player from Netflix a while back I tried to emulate the github profile page let's see if this loads this so just with bear CSS can you emulate this page in the layout and all that good stuff that's good practice overall how to type like typescript has its place typescript is cool if you're working on a project that other people are eventually gonna be working on if you're working on a team it's it's like self-documenting code which is cool the errors can be very cryptic and my editor is having a really hard time whenever I create new files with detecting that is the right type and stuff like that doc is saying how would you translate a style like that to format like input plus input to only add margin between elements in this case I could just select the first UI text field root so there's a CSS selector for that like first child so I could have done first child and added its margin-bottom to be one rim that's that's a possibility basically any valid nested CSS selector can go in here and you can nest it even further so I could say and then for any span that's inside of that element with that class apply the styles there as well but technically this I think I could you could do exactly what you're saying right like this I think I could say that with the nested selector that with a margin top or bottom margin top of one ram and that's only gonna select one of them which one I don't know see which one is selected it's elected the second one yeah so that's the selector so that says select the element with the with the classroom UI text field root select the one after it and apply a margin top of one rim to it so that did it I'm okay with applying one rim to both of them now one love says I think web development may shift into DAP development so the web dev people will just be employed by new companies and probably an even larger opportunity exists yeah so like decentralized applications based on crypto currencies sure uh thanks Jay yeah this this project there is no checklist we're just just coding it as we go yeah let's take a sip of water you I think that that would work this this is this is vanilla CSS like at the end of the day it generates CSS classes and selectors so if we would have done that it probably still work the way that you're intending and Haken code what's up yeah and hello IC killer I don't know this morning I woke up and I wanted to stream and I didn't know what I was gonna stream so I decided to do this without any plan and there were a ton of people watching this morning so it was really hard to even get started let alone create a checklist I don't know but what we need right now is a button a button to submit this form so let's look at components let's look at button and thanks for the follow the DJ sizzle welcome to the show let's go this one button variant contained and we'll add that right at the bottom of the form we are building a guestbook but ultimately do that's the one I want um altum Utley we are trying to demonstrate how you as you would you would configure in a symbol a react application that has many different things it excuse me it has typescript that's manage that so it has typescript we have code style management with es Linton prettier and the Airbnb config we're using react router that's all set up and configured we're using a state management library called easy-peasy that's all set up and configured and we're using the material UI component framework so the main point of the stream was to show how to put all that together into one react app now we're kind of just building the app and in a bit once we get this form going we're gonna actually write some code in our custom ezpz store that will add new things to the store based on this form that's the plan oh nice yeah this morning was a mess I yeah I was a mess I'm telling you every time I try Firefox like within 30 minutes of using it it for web development I find something that's broken particularly the the thing that was broken when I first Edyta a few weeks ago or CSS transforms I was getting these weird jittery things happening when a CSS transform was applied that did not happen in Chrome so I didn't want to deal with that anymore Oh an auto scheduler that's pretty cool interesting so brave automatically implements peer-to-peer daps distributed apps it's not full stack yet but I think we're gonna we're gonna create a quick back-end quick one hello Louis these are blue switches I didn't install them this is like a super cheap mechanical keyword if you do exclamation mark keyboard you'll get a link to it but in the description that says they're blue switches I know nothing about switches and I think you commented on my video earlier I appreciate that I was gonna comment the same thing that we literally didn't get cart started coding in till like 30 minutes in but yeah Fernando's saying the web console is broken that's not good Microsoft edged insider I'm not gonna click that link but cool we alright so we have a button we're gonna say add entry is gonna be booked the text on the button let's see what we get nice we can click this button let's make it primary so it has a nice color make a new color primary nice blue button very good and I want it all the way to the right I believe their layout system like a actually I think the box is a flexbox let's see I believe they have a component for doing like flexbox style things without flexbox classes and such let's search okay box display flex is what we're gonna do so we're gonna we're gonna wrap that button in a box and make it a flex box with justified content flex in so it puts the button all the way on the right so got ourselves a box box box I want to import that from material UI like so that needs to go up there and then we can do justify content give me autocomplete flex flex end Alex fashioned and that should put the button on the right very good so now we can type our name our content what is this even and then when we click Add entry we're going to send it to the store but before we do that we need to validate the form so let's install the active form so this will be interesting for those of you that haven't seen or heard of this thing before so react hook form is a library for validating your forms using hooks and it's pretty sweet let's just look at getting started we're gonna install react hook form and then it gives us this nice little hook called use form which gives us things where we can like register an input and in the cool that one will the cool things about it is instead of how using controlled components and so this is like the standard way of handling inputs that most react form libraries use they are controlled components meaning there's an underlying state variable that keeps track of the value of that input at every single key press whereas this does not use controlled components it uses a ref to the underlying Dom element and when it needs to get the value it just uses Dom Dom code to get the value of the thing instead of having an internal state value which reduces the number of renders on your components that said let's install the things so our app typically has been running into issues if we try to install things while it's running so we're gonna kill it install react hook form and let's catch up really quick [Music] an example with login form with use reducers so I'm gonna show a login form with easy peasy which is kind of like reducers you could use reducers if you wanted to but I'll show that in a second what am i using for back-end nowadays I'm in love with no connects Express in Postgres so I'm because of my job we actually I mean I could have used Postgres if I wanted to I think but most of the previous projects at the job I'm working at used my sequel so I'm using my sequel in previous projects I was on we're using sequel eyes which actually don't like that much and in my latest project I'm using objection with my sequel and connects with node and Express and feathers Microsoft edge eventually come in to limits and Mac who would be who wants that stop it Microsoft what are you doing full stack dot mops hello is saying where would you recommend learning react I know some JavaScript I will direct you to the coding guard no I mean I have some videos on react if you search coding garden intro react there is a video and some people like it some people don't but some people do you might be one of those people so you can watch this video that's a like a basic intro to react it was recorded over a year ago so it doesn't talk about hooks but it talks about the basic underlying concepts and reacts you can check that out but if you want something else check out a cat of mine they have a free course on YouTube and then they also have udemy courses if you're a you know me person go into playlists go into I thought they had a react one yeah react j s+ redux basics they start off with just react Redux is extra that's beyond you got to learn you gotta learn react first though i think maybe they combine the two but definitely check out stuff for my cat of mine they're great and then also check out brad trabber scene the react.js crash course I'll send you this one and if none of those you don't like any of the host searched on you to me there's a lot of react courses on udemy yep yeah that's crazy well the thing is they probably didn't have to work that hard because it's chromium anyways validation is for squares no validation should be a thing that every developer does and nobody like there's so many developers that don't do it and it it's it's so bad like form validation anyways and also showing like error states like yeah I'll show you we're gonna we're gonna make it we're gonna make it look nice for view I've used the built-in validations in beautify that's about it but I've looked at viewlet date before it looks pretty cool objection your great at hello freaky bugs welcome uh dev ed is cool too does he do react courses yeah yeah go for it bin feel free anyone read these ordered them just seeing if anyone has a good experience with them web design and HTML javascript jquery let's let's see I can do I can do this here we go I think this this might be the one that I'm thinking of yeah this is a good one a lot of people recommend this so I personally have not read it but I see a lot of people recommending this book so I think you made a good choice and hello Quran welcome sarcastic in hello Oscar everyone does react courses because it gets more views it's so true okay I'm gonna hide my screen for a second and I'm gonna show you some analytics for one of the react videos that I did it's insane I did this video over a year and a half ago it's like a four hour livestream of me just figuring out how to make a map app with react and it just constantly gets views it's gotten 178 views in the last 48 hours let's look at I don't know I want to see some better spent sets so let's look over lifetime yeah I'll share it I mean 44,000 people have watched it some 114 people have given it a thumbs up so maybe you'll like it too but I do believe the simple fact that this is a react app that's using Express and MongoDB like people go crazy for this kind of video so check it out if you want to but there's that there's that and see it was streamed on July 24th and here is the the view the views chart like it's just getting hundreds of views every day I don't know I should make a react course or something right hello Hakan welcome simple to follow react course let's check it uh the net ninja yeah yeah totally um I'm subscribed to them I haven't really watched any of their videos but I am subscribed so it seems like a good resource when I'm doing responsiveness which your reader make everything from scratch with media queries or importing third-party libraries like bootstrap of predefined classes it depends material material UI it might not yet mature you I has like certain break points for different device sizes but in a recent app I built our designs had a different specification so I just created my own break points and then reuse them all over the app but yeah I don't know I could there's a lot there's a lot of things I could do Oscar read both of those books and they recommend it it's react courses get more views is jQuery the worth learning still I think so like if mainly because there are so many legacy applications out there that still use jQuery and when you get hired somewhere you have no idea if you're gonna be working on an app like that so just knowing the basics of it I think is worth it if you're building a new app you probably shouldn't use jQuery but yeah and thanks for the follow commies lair I haven't looked into react suspense I've seen some stuff looks pretty cool and easier to manage I saw I saw the like the tweets and the posts about it but I haven't looked into it further than that it doesn't seem that big a deal I think the main thing that it adds is it prevents a component from rendering altogether until some been dissatisfied or as currently you could use like a ternary and technically it still renders it just renders nothing or something else but it seems cool I do have affiliate links casual gameplay with a donation thank you casual gameplay who says hi CJ thank you for the stream you're very welcome yeah we're doing a lot of chatting today I mean we always do a lot of chatting what am I saying is we made a forum we have a button but we're about to start validating it with react hook forum and I thank you for your donation it is very much appreciated but I do have affiliate links so when you when you click my keyboard link that's an affiliate link but yeah the coolest thing I've ever coated I don't know I don't know um I don't have a dark theme on all sites but I do have dark themes for specific sites but it's a it's a plug-in called stylus do not install the thing called stylish that thing harvests your data and tracks every single single website that you visit this is the the plugin that I use and then you can create your own custom style sheets or you can find style sheets on user style is about org so if you search for like github you can find like a dark github theme and then install it yeah github ice dark basically people submit their own custom style sheets you can install them and then they will always be applied to that website that's basically what I have for for github and thanks again casual gameplay for the tip fire can I do a quick explanation of what validate means yes so a validation is when you prevent the data in a forum from being submitted unless it's valid so right now I if I didn't enter a name and I didn't enter content and I clicked add entry what I want to see are error messages I want to see an error message pop up that says name is required I want to see a error message pop up that says content is required or if content needs to be a minimum length I want to see an error message that says your content is too short so validation is making sure that all of the elements in your forum are valid before you allow the user to submit yeah no worries it's a it's the point of it all nothing on the coding garden is quick and thanks for the follow Empire IT tech view three changes are cool I'm probably gonna use a lot of of the composition API especially because I've been using so much so many hooks in react hello Bob hello Dominic welcome yeah cool excuse me and uh good morning code with Dinesh in hello Dominic we're about to add some validation to this form so we just installed a react hook form so we're gonna start the app back up we're gonna get this going so in this component here that has the form with these text fields we're gonna bring in react hook form and react took from performed as multiple things for one it's gonna keep track of the state of the form and when the form gets submitted we're gonna get an object that has all of the data on it the other thing is it can handle validations so if there are things that are invalid we can we can get access to that and then show them in the UI so we're gonna bring in use form from react hook form we'll pull that in up here at the top and then inside of our component we can say use form and we're gonna get access to this register function the register function is what you have to pass to each of your inputs text areas select boxes inside of your form to be able to keep track of the state of that individual thing so right here we're gonna say register equals use form like that and then now we can pass this register down to each one of these things so material UI exposes a prop called input ref which for words the ref down to the underlying input so refs in react are a way of getting act access to the actual Dom element not the virtual Dom but the actual Dom element so here I can say input ref equals register and then similarly on this text field I can say input where F equals register and the key things I need are each one of these text fields needs to have a name prop because the name prop or this one the name prop is what it will use to take the data that's in the form and put it on an object so we need the name we pass it in register and then we get access to handles so what we'll do is we'll make a basic little submit function on submit it's gonna be a nice nice little function that gets access to the data and then we're going to log that data to the console and what we'll do is on the form will say on submit equals handle submit and you pass in on submit so handle submit comes from react hook form you pass it the function that should be called whenever the form is submitted and now this function is gonna get called when the form is submitted right now this we need there's some type script errors so first this run function returns void so I'm just gonna add void and then the other thing is right now data has in any type so in a second we're gonna create an interface that represents the actually we can reuse an interface I have a plan let's do this before we go any further so this form is representing some data right this form has a name and this form has content we created some interfaces earlier like earlier today one called guestbook entry so guestbook entry is like a contract it describes what a guest guestbook entry has and as you can see it has name content and submitted so what we can do is we can use this interface and whenever we call use form we'll tell it that the data of this form is represented by this interface so let's import this interface into this component it's import guestbook and trade from up one directory up another directory go into interfaces and grab the guestbook entry and I believe now whenever we call use form we can actually pass in the type here guestbook entry and right here we can say that the data we're getting back is of type guestbook entry so now we've typed two things so when the form is basically we're getting an object that adheres to that guestbook entry interface it's gonna have a name and content it won't have submitted we're gonna add that whenever and whatever gets added in hello Solomon welcome to the show that should make an error message you are wrong all right we want to see this form submitted though so this should do it I think on the button I'm just gonna add a type of submit shouldn't be as code have auto imports it does it doesn't always detect them though that's some of the issues we were running into okay can you make an optional prop in an interface yeah so the way you do that in typescript is with a question mark and actually I'll do that here that's a great point so if you had a question mark then that means this can be undefined or if it's not undefined it should be a date and so that's the question mark and so that makes sense here because we don't we're not we don't have we're not having them enter the submitted date in the form okay I think we should be good to go we're not doing any validation yet but what should happen whenever we click Submit we should see an object with a name property and a content property that is whatever we typed into a form so let's give it a try refresh Deb tools oh yeah I need to add some keys on one of my maps but regardless my name is free ebooks my content is optional drop this and now it doesn't work let's see we did get this button a type of submit when it's submitted we're telling it to call handles submit use some generics I don't think we're gonna write code that would need generics but technically the person that wrote this use form hook used generics so that way we could do something like this when we're actually passing in a type to type it what'd I do wrong not getting any airs I'll fix this map and Kiara really quick she made our home component we need to just add a key to this card I'm gonna set it equal to why isn't it Otto refreshing you each child in the list should have a unique key prop okay I'm gonna kill this app and restart it error message you are wrong hmm all right let me catch up really quick object is possibly undefined so that's this is actually a good typescript error so because our interface now says that submitted could be undefined we need to check for it in our code so I'm just gonna say I don't know honestly we're gonna add an ID we're gonna add an ID property to this interface so we're gonna say ID is a number and then whenever we for our initial state we're gonna give it an ID and it's complaining it's like hey you don't have an ID property ID is missing because we added it to the interface I'm just gonna do a date dot now which should be like the timestamp number four right now okay or not and I still I still need to fight still need to handle submitted where are we in home I really need to say if entry dot submitted then do that otherwise in D string okay clear the console test test to add entry it works I had to restart the app I don't know why but it works so when I click Add entry on the form submit is getting called it's creating this object adding the properties it's a beautiful thing like if you've ever had to create some state for a form in react from scratch it's kind of a lot of work you have to create like State for each individual input when those things get called you need to update the state and right now this is just handling all of that for me with with simply just this register item in the Hindle submit so it's great code with Dinesh says check out Roberts my awesome react react structure I think it's the best folder structure okay check it out who is Robert hmm clientele telephone this is called import cost you can find it on the vs code store what's up what's up you're welcome Solomon is there anything like a fetch interceptor like Axios has interceptors not that I know of I mean you could do it by overriding fetch with your own interception function like overriding the global fetch but as far as I know it doesn't have the same concept of interceptors like Axios excuse me we figured it out Louis so I've just been having tooling issues like I restarted the app everything works fine now but this is this is actually what you have to do so if we look at the docs for react hook form you pass the function in to handle submit and you'll notice that we don't have to do like event.preventdefault or anything like that this handles submit function that's coming from the hook is handling all of that so I really really don't get what you're saying that's okay I did a two hour stream earlier today where I built up all of this stuff so this is a lot to take in especially if you didn't see the stream earlier today types trip decorators oh right decorators just seem what's the word it seems boilerplate e to me I don't like it I don't like the way it looks I don't know thanks for the YouTube sub Emmanuel yep you can create namespaces in typescript do that in your template you're weird you're weird because I'm coding and there are 32 people watching on twitch sorry 32 people watching on YouTube and 38 people watching on twitch and you're just one of them and so I gotta I gotta keep up with all the chats I got to write the code I'm doing a lot of things here ok so now let's do some validations if you look at the the docs here it's possible to use yep for doubt validations and I think I'm gonna use that I'm gonna do that yeah and there's a pizzeria happening 24/7 so we do we do a lot of things here validation schema so in the reactor form site you can see that you can create a schema with this library called yep and then when you use the form you can pass that schema in and it will automatically use that schema to validate each of the inputs and then you'll get access to this errors object which you can do things with so let's do just that so we're gonna install yup to do our validations right now the validations are gonna be super basic like maybe we'll have a minimum length on the on the content like minimum length of 10 or something like that but we can do some validations so kill this let's install yep mmm cool nope I didn't want to do that again we could do that we could do some sentiment analysis but no I'm just gonna make sure that the entry the content is longer than 10 characters let's start it up mm-hmm and then now in here we're going to import you up and create our validation schema so let's import star from yep import star as yep from yep I think I'm I think I might actually need to install yep types let's see could not find a declination file yeah so we also need to install at types /e up so since we're using typescript we can install this package in typescript we'll we'll know about its types and can provide suggestions yeah so install that I cannot do a backflip even on a trampoline like as a kid jumping on trampoline I can't do a backflip I think I might have try different I can do it like a backflip under water okay no I don't use my Domino script when I order pizza I just used the the website it was it was fun to do though you would risk breaking your neck yes flipping the direction you can't see is very scary I believe it I mean I yeah like it is okay so we're gonna call this the guestbook entries Timo this is an object it has a name we'll say string will also do dot trim I know that that's built into you up to prevent just people putting spaces as their name and then we need to validate the content so I'm gonna say that's a yup string we want to trim it so it can't just be whitespace and I believe we can say min tin and so that will say that you can have a minimum number of ten characters and then let's also do a max of like 200 characters so this schema will validate an object what's just complaining about oh this will validate an object that you pass into it and if the content is less than 10 or it's empty or it's greater than 200 it's gonna throw an error so that's a good thing oh yeah so yep is very similar to joy but yep is for the works in front end code last I checked joy still didn't didn't work in front end is mainly just for back end yeah exactly yeah you do a backflip once and then that's that's the end of it all why not just test every program on submit you could you could do it manually but the what I'm gonna show is what's cool about this is we can integrate the error messages that pop up from these validations and we can integrate those with the actual form itself so yeah okay so we have our schema and then we're gonna pass that in as the validation schema when we call use form so use form or pass it an object will say validation schema is our guestbook entry schema like so and now it's going to validate it and we should get access to this thing called errors and for now we're just going to log those errors here so if they happen we can see what they are yeah so this is a minimum character length and a maximum character length yeah at least that's the plan hopefully it works that way if not we'll look at the the yup documentation so now we pull these this error object from use form we're logging it to the console and so when we submit the form we should see some errors at least in the console let's try it so we're gonna submit an empty form and now these are our errors and we get a message that says name is a required field and we can see content content must be at least 10 characters awesome so let's actually use these these errors on the field itself so part of material UI a text field you can pass an error too and this is just a true or false whether or not this field has an error on it and it has some automatic styles that get applied to it so right here I'll say error is watch this errors dot and because because because because our use form is typed with guestbook entry we automatically know what are the possible errors that could be on on errors so we get Auto completion and I care about if errors dot name is a thing and then for content I care if errors got content is a thing I am getting a type error though because it wants a boolean so I'm just gonna do not not to turn it into a bullying because if there was no error for that field it wouldn't be a property on the object so it would be false cool so just by doing that we now get some error colors and so this is these are these are the default error styles for material UI so if you look at components text field you can actually you can override the color that they show up as things like that but just like that now that we passed that error property down that's and turned it into a boolean these show up is red because they have errors on them and then the last thing to do is to actually show that error message so let's do this let's say I think it's called is it helper text see you later Dominic thanks for hanging out yeah helper text and so he'll protects t' i think we'll say if errors name is a thing then errors name dot message otherwise nothing and we want to do a similar thing for the content so if errors dot content is defined then we want to show errors dot content message cool so just like that we should now see error error messages on the form so many of that name is a required field content must be at least ten characters and now as I start typing the validations update and it loses its Eric Eric color and you can see here this won't lose its air color until I type at least ten characters so like help hello world and now it's valid however I believe on a text field we can actually show the number of characters like a character count it's like built-in I think yeah you can change like the success validation style the error validation style you can do a lot of a lot of customizations I feel like it's a thing let's see if we can get a property like alright not rose max oh wait did you ask a question Clara tofu oh why would we have a min oh just because I don't want someone to submit like a very short entry that's the main thing like they have to at least type a few words rather than just like one word that's that's the main validation awesome so uh yeah validation is happening that's a beautiful thing so I refresh yeah and the thing is we can we can change these error messages as well so the yep library actually allows you to pass in custom messages so right here we could say like just required so instead of saying name field is required this will just show the word required and we can also pass in a message here must be at least 10 characters can be no longer than 200 characters and so now it'll show those error messages instead required must be at least 10 characters hello world and then if it's over 200 oh that's not what it can be no longer than 200 characters cool thanks Bob Andreea says I use the material UI components at work but had to overwrite almost every styling you see where you work on them is like if I was looking at my code yep I'm doing exactly the same thing so what I actually ended up doing is like our our our styles are so custom compared to the built in material styles I actually defined my own input component in my own button component in my own select component that actually wraps the material component and adds all the default stylings to it and then exposes properties so you can like modify it mainly because I wouldn't want to have to repeat that code everywhere in my code base but yeah I know the fields what are some advantages of material UI over other UI frameworks and tools it's one of the most popular react ones like there are a lot of people out there using it it's very highly customizable like it can get very verbose and cumbersome to customize things but it is customizable like I can change the text I can change the colors here I can change the border radiuses and the max width and the minimum lifts like everything is extremely customizable which is pretty cool not all UI frameworks are like that some of them are but that's one of its advantages I don't know a lot of people use it I could yeah I wonder if it's built into yep but I could I could actually no I could I could do this so you can say dot match and you can say matches so it needs to match this regular expression kind regards and then the error messages content must end with kind regards oh man this this will technically do it I'll scape that so it must end with kind regards let's see it happen at entry must be at least 10 characters hello world must content must end with kind regards high regards hello Paul why dooble I don't know what that means yo mama says they're using blueprint JSF I've heard of that that component framework cool components buttons I might have seen this before it looks kind of a github II like the way the github UI looks Arno all your bases are belong to us github release and internet that's pretty cool thanks for the follow Kauai kawaii perfect clientele Ivana is asking to react in view and most frameworks prevent things like cross-site scripting in sequel injection by default or do you have to handle them in your code they prevent them by default so in react if you wanted to allow yourself to be cross-site script Abul you literally have to do something like this let me show you give you say dangerously set inner HTML and then you can set like a value here and let's see yeah I can make this a self closing div but it's literally called dangerously set because there is no escaping here string is not assignable oh yes so then I actually actually need to pass in an object with an H underscore underscore HTML property that is the string and then what's this complaining about yeah and then I have a linter rule that says don't do this but let's see if it'll actually leave and compile no it will and then there we go we see hello world but we don't actually see the span tag and if we inspect it it's actually the HTML so in react the kind of I wouldn't say the only way but the main way to become vulnerable is to use dangerously set under HTML and then in view you have a VHT ml directive that'll let you set the HTML so if you're using either of those things you would definitely want to do some sanitization otherwise they get escaped yeah I have used double DubLi not operator oh yeah I have that's because errors dot content is an object and error is a boolean or it needs to be a boolean so I need to turn this object that either exists or doesn't exist into Abilene that's just why I have not not Augustine says you're also I'm learning so much from the few days of watching your live stream well it's writing hangout I'm glad I'm glad you learning stuffs alright let's get rid of this silly kind regards validation and now now I think we're ready now we're ready to send this data to the store so basically what we'll do is inside of this on submit will fire off one of our our custom actions silly we're gonna fire off a custom action that takes what the user just entered into the form and then puts it into the store here into this intro user right right so here's the plan first we're gonna go to the interface we're gonna go to the guestbook model interface and on the interface we need to define an action so I'm going to create an action called add entry and it's going to be an action like of type action and we have to pull that in from easy-peasy so let's look at how we do that ducks type script tutorial typed actions here we go so we need to import the action type from easy-peasy and we're gonna say add entry is of type action guestbook model and it's going to take in a guestbook entry like that so this allows silly hello and neon cuts welcome and hello majestic guy welcome so what we've done here in our interface we're saying the guestbook model should have a property called add entry that is a function in action that takes in the guestbook model as the first parameter and takes in the guestbook entry as the second parameter so that's our interface now in the actual implementation we need to implement this action so this is the interface now we go to the actual a guestbook in the store here and you can see it's complaining because add entry is missing so now in the implementation we need to actually implement it so we're going to import action from ezpz and right here we're going to say add entry is an action where we're going to get access to the state and we're going to get access to the entry yes I think I think that's oh no we need to pass it a function yeah we know we need to pass it a function that gets access to the state and the entry so we invoke action and then pass in well little arrow function like that where we can actually update the state or change the state so this is one of the cool things I like about easy-peasy is you can actually it looks like you're modifying the state but under the hood it's doing other things but what we can do we can say State DOT entries stop push entry there's like that and this will take the entry put it into the array and behind the scenes it actually creates like a real react State update so it's not modifying the object it's creating a new copy that has that value inside of it and it shows up in the Redux dev tool so I'll show you that so now that we have this action we need to use it inside of the form so in the form here we need to pull in use use state action use action like that they're in our hooks here hmm this thing use store actions I think I think that's what we want and where are we in the forum we're gonna import you store actions import it from hooks and then now right inside of the component we can get access to that at add entry action and then basically we'll just pass add entry into handle submit and we'll be good to go I mean actually we might do it here so that way we can clear the form but let's do this we'll say add entry equals use store actions we get access to the store will say State guestbook add entry just like that and now we have this add entry function and all we gotta do is call add entry with data like that and now this will actually put it into our store our then our home component is already listening to the store so if we look at our home component it's already looking at the entries from the store and so that other component will push it in this component we'll see that there's a new value and then we'll see that new value on the page though I just thought of something instead of pushing it let's let's put it at the beginning of the array so entries dot shift unship inserts a new element at the beginning of the array so we're gonna take whatever the user submitted and put it at the beginning of the array and just like that no errors it's gonna work on the first try my name is Bob and my content is this is so cool add entry and there it is it gets added we do have an error and I think the error is it doesn't have an IDE and it doesn't have a submitted date we actually need to handle that in the action but that's this is easy-peasy for you it's that easy so we have the action we call it it gets added everything works beautifully but right here before we put it in we should actually should say something like entry ID equals date that now and entry dot submitted equals a new date no Purim reassigned I'm gonna disable that yes lint rule specifically because in easy-peasy you are reassigning the parameters no brandy si that there we go and now refresh clear it majestic high content this is pretty cool cat emoji no ceiling emoji head entry there we go Enzo it pops up so one thing we can do is we can reset the form so after you've added an entry this stuff just disappears let's look at react hook forms I think there's like a reset yeah um so you can actually just call reset inside of our submit function cool cat yeah so we'll add the entry we'll reset the form but we do need to import reset from this use form yeah like that I think I should do it in our home component let's add a little bit of styles to the card because right now put this over here did i hack CJ Johnson did you try majestic I actually that's super interesting yeah because I know majestic I you do like security scanning and stuff like that so I totally forgot that I gave you right access to the the vs code session so you might have been penetration testing it I totally forgot but did you find it evening that's that's really funny um doc is saying I feel like the design is too slick it needs some sign our guest book and my guest book it's so true like materially I guess what he found everything well probably the only weird thing I have on here is like I removed most of my personal documents from this computer Oh must be at least 10 computers 10 letters cool so I want to add some some margin between these these cards I was doing CSS and logo design I would never try to hack you and if I did I would tell you via PM Thank You majestic guy then what did what did Andrew Lane mean by that but I appreciate that though shout out to this awesome logo design weird garden actually let's play a round of word garden anybody want to join in CSS keylogger that's funny though well when someone mentioned that that that hack yeah this thing's been deployed of course I'm gonna go for team one and I also added this activity log so you can see what letters people guess and it will automatically focus whenever it's your turn to guess II nice got a point got to be ready because basically the first person the count is so high because I wrote a bot I wrote two BOTS that were competing against each other and they had access to the word list incorrect guess F what could it be nope now there's no I thought there would be an eye Oh nice you nice we did it but yeah I wrote two BOTS that were competing against each other and they got the score like well above a thousand but basically they would determine all possible words and then narrow it down from there and by like three guesses they knew what word it was like instantly and see you later Fernando thanks for hanging out with us you're very welcome for all the stuffs we do here yeah what could this be oh that's naughty block cipher row mode of operation very good cool this is fun probably this Sunday we'll work on turning this into an actual garden and we'll make it so that the team has to vote on which letter they're about to guess because right now you basically have to be the quickest of the draw and I was I guess I was I was that's a lot of ease [Music] datagram data game Datagram transfers security transport security Oh empty element very good alright I'm done with this game but that was fun good job everyone Oh someone asked me to Google this earlier my awesome react Redux structured structure let's take a look do-do-do-do-do-do so they have environments models selectors stores utilities and views it's okay I've seen better like theirs they're still technically like breaking things down Zin in two totally separate files like I would actually combine the actions effects and reducers into a single file and I would actually put it right next to the component just so it's all in the same place I don't know it's interesting if you if you've never structured a large app this is a good place to start I would say do you still need Redux if you use hooks in context no and I mean we're using easy-peasy which is written on top of hooks and context oh and one thing I didn't show you yeah let me show you this is this is the coolest thing watch it if we go to the Redux dev tools look at this all the things that happen get logged so we have our initial state which is that entry of 1 CJ thing and then when we call add entry that automatically logs in action in the redux dev tools and we can see that the action included that payload with like tests and things like that and then we can see how the state differed basically a new thing was added to entries it's dope so like you saw the code that I wrote I did not write a single action creator I didn't write a single like all I did was I where are we here I implemented this model which has an add entry action and ezpz takes care of the rest a tox actually automatically will log to the redux dev tools for us yeah and it's it's not using redox redox dev tools have their own API for like adding things to it so yeah that's the thing so technically we could start off the app with nothing and then we can add an entry oh yeah but we wanted to add styles here's the other CJ what is this even cool so I want to add some margin between the cards there so if we go to our home component why don't I have oh um I don't have any monetization enabled on twitch so twitch has a now Facebook even know is everywhere test you I mean they technically are our owners of the Redux dev tools but yeah but I don't have any monetization enabled on twitch because on twitch if you become an affiliate which is what's required to like get subs and stuff like that they have an exclusivity clause that says you are not allowed to stream simultaneously on other services and any stream that happens on Twitch cannot appear anywhere else for 24 hours so right now I stream on both YouTube and twitch so I haven't enabled monetization what I might do is pretty soon I might actually just I might swap back and forth so like two days a week I stream on Twitch and two days a week I stream on YouTube just because I've already built up such a huge following on YouTube a lot of people haven't followed me over to twitch yet but that would allow me to monetize I'm on both Zn morning Akash welcome to the show why do team timeouts not remove points oh I don't know because because basically the the the game is running 24/7 and so if you were running 24/7 it would basically be timing out back and forth between each team and then the store the score would be like super negative that's why I'm losing against no one because of it oh I got a letter I'm just playing Angie right now basically hmm I don't know what the heck this is is it that's not even a thing first interactive what is that I don't know what this is first it's in the glossary Indian glossary first CPU idle is a non-standard web performance metric that measures when the user's window is quite enough to handle user input or what is termed as minimally interactive interesting okay doc is saying team chat would be fun for the game then you could randomly pick one player on each team to do the voting and everyone else tell us what to do yeah that's the plan I like basically you collaborate to decide what letter will will be guessed next I feel like it's kind of like Family Feud in a way I don't know maybe that doesn't make any sense at all all right we're trying to do is add styles let's do this so on the home we're gonna add a new styles file we're gonna import make styles from material and then we're gonna export default make styles we're just gonna create a card style call it entry card and we'll say margin top and bottom one rim and nothing on the left and right and now we'll use these styles inside of our home page so we are going to import use styles from that Styles file we'll get access to the classes and then right about here we'll say class name equals classes dot entry card should give us a margin Oh No cool yeah and then there there would also definitely be a countdown like your team has 30 seconds left to guess and otherwise it goes to the other team oh yeah the other thing is we'll create well basically create like game sessions so if your team or timer does run out then we'll give negative points because right now there are no sessions it's just one big global session but if you had sessions then you know that people are actively playing so yeah okay what else did I want to do here I think that's mainly yet we have validations we have store actions I think the the main other thing to show would be doing asynchronous actions so now instead of instead of our store just being like a simple object and like I start a simple array and a simple push we could talk to an API that lists the entries and makes a post request to create a new entry it adds the amount of letters it added yeah so like if you guess a letter that is in the word multiple times you get that many points is that way me yeah but should I so I've been streaming for about an hour and 40 minutes it would be nice to go watch some TV what do you all think do you want to see me hook this up to an API what what what about what about this application are you interested in in that if you've if you've written react apps before or and if you've written react Redux apps what would you want to see this thing do that you normally do with like a reactor Redux app that you haven't seen yet because we have our store like I said it's very basic but we have it so no go watch TV all right here to two votes for go watch TV I kind of want to hook it up we could spend we could spend 20 minutes doing it I have no problem spending 20 minutes hooking it up to an API the thing is I'm not gonna build an API I'm gonna use something like JSON JSON server Oh No how timely all right so I actually I have oh no I didn't write tests should I'm not gonna write tests I think I said I was but I'm not going to but I have all seven seasons of malcolm in the middle' I'm on season 2 now I started it like a couple days ago I also have like 12 or 13 seasons of king of the hill and I've been watching a lot of that and I have all eight seasons of Game of Thrones I just started season 5 oh no I'm in the middle of season 5 yeah Oh king of the hill all right let's hook it up to an AP and we're gonna do a simple API what's this boring so I hadn't I had never watched it before so I had like so many people talk about it I've literally never seen it and now I'm finally watching it and I kind of like it it's cool I like the stories I don't care if characters die like no character is sacred it's cool it's all cool stop at 6 and make your own ending okay I'll think about it like if I'm really satisfied at the end of season 6 I might stop okay we're gonna make a directory guest book API we're gonna edit it we're going to install JSON server The Witcher oh I saw I want to watch that on Netflix but I'm gonna finish Game of Thrones and then I'm gonna start watching The Witcher yeah I've done this before I need to look at the JSON server doc so JSON server is just like a really way easy way to get a JSON server up and running like an APM race JSON API that just saves - a JSON file I'm not gonna do that mr. robots great I don't know if I've watched the latest season III like diligently watched the the first few seasons as they came out but I stopped I stopped keeping track of it okay so we're gonna create a DB JSON that just has entries in it like that so this is this is our API it starts off with no entries and then you can make post requests to it I'm curious I can you do validation yeah we could add a basic validation middleware that makes sure that it has I think we'll do that yeah so B this'll be fun a super simple JSON API let's create our index J s and then we should be able to set it up like this so bring it in create it use it community oh you're the TV show I watched the first few seasons of that it's funny I like it I don't watched it recently though okay we're bringing in DB JSON and how would we add validation yeah ready this oh yeah so I need to do I need to add body parser Wow this JSON server is pretty interesting so we're using our middlewares then we're using the router but we'll do this if the method equals post will say wrecked up body got submitted is a new date like that and then let's just install joy on the back end cuz why not and then we can do a very similar validation that we're doing on the front end but we'll do it on the back end ooh do you need to install it from that at happy / joy yeah it is cool we'll do that what did I just install you cool so now that we have joy I'm gonna copy my schema from the front end and we'll duplicate it using joy on the back end so here's our schema hmm actually do I do I don't need to validate on the back end I'm already validating do it I I don't but I am gonna add I think this is fine because this is adding the submitted date to the body it's fine okay let's start it up we're gonna listen on port 5450 for and we'll just add a start script sentiment if sentiment analyze text is less than zero don't be me what gets me does it work in front end code I might do that that's easy enough do you know index page I guess yeah it absolutely would be good coding but good coding would also be to not use JSON server because JSON servers just saving it to a JSON file so really I'm just creating like a dummy API to show how API requests would work with the front-end that's that's the main thing I don't know let's just get this going alright servers running and it's running on port 54 54 so if we go to localhost 54 54 slash entries get back an empty array cool so this is where we want to make our API request to on the front-end so that's all I'm gonna do for now this is we're gonna have that super simple API and now I'm gonna hook up the front end to it so we will do this what we need in our guestbook is we need an action that will load all of the entries from the backend on initial page load so we'll do something like this get entries and the thing is this needs to be a thunk because it's going to be asynchronous and easy peasy what are we doing easy peasy also has a thing called thunk which you can use to create a custom thunk so I'll say thunk which gets access to the state and we'll just say we'll make this an async function so we can do some some fetching and I'll say a response equals oh wait fetch with fetch that URL and I might be able to let's see state dot oh no I'm not gonna get autocomplete yet because I need to add it to the interface but basically what we're gonna do is once once we get back to the response we're gonna set it on state we're gonna send entries to be that response and we have a new YouTube member Sean thank you so much it hasn't appeared on my screen yet but it will soon and an avocado no way very much appreciated John let's wait for it to pop up it's gonna happen gotta happen that's awesome there it is sean has become a YouTube member it technically worked out Andrew thank you so much and as an avocado you get to vote on one live stream for me to do this month so it's the middle of the month I'm probably gonna send out a message soon to all the avocados and there are currently four avocados hype hype so you for avocados choose a thing I'll research it I'll do a live stream on it and there's a there's a specific channel on the discord for avocados so I'll look out for whenever you join the discord but if you don't get added to that channel DM me I have to do it manually because youtube doesn't isn't integrated as well as patreon but also as a member you can use all these awesome emotes like the CJ smiley mode or the CJ s emo look at the JavaScript emo though I haven't yeah I haven't added these to my overlay yet cool but thank you so much John much appreciated alright where are we we need to on our front end in our interface create this thunk so we're gonna go to the guestbook model and just like we added add entry here do the same thing but we're gonna bring in funk they're gonna say get entries is a funk that takes in the guestbook model just like that yeah like that so now in our implementation it should stop complaining and if you look at state yeah so the thing about a thunk or at least like in this case is we don't directly modify state we can just call any of our existing actions from within it so what I need to do is I need to add another action called set entries that will actually update the entries so I'm gonna create one called set entries which is an action which takes in the state and the entries and right here we just say state entries equals entries so it's a simple little action that's going to overwrite the things and then in here we can call that action and we really need to await it so we call it will say entries is a late response JSON and then we'll pass it in the entries so that B should be good but now in our interface we need to define set entries it's fairly similar it's an action that I don't know what to call this like those of you that use languages that use that have generics in them what do we call this like an action of a it's not of a type it's basically yeah I guess it is of a tight what do we call these these less-than and greater-than I know in the actual implementation it's a generic so like if you go to the implementation you can see model it extends an object but because they've defined it like this that means you can pass in any thing any any possible interface here it's a type argument is that we would call it but basically you can pass in any interface and then the underlying code make sure that that both those things adhere to that interface parametric polymorphism or maybe in a Java development 8-bit tacos is type argument it's like I consider the arguments to be the things that are like passed into the function it could be though like these are the arguments like ultimately state is going to be of type guestbook model and entry is going to be of type guestbook entry but when we're defining it we use that a bounded type I like that I think is I used to do this all the time in c-sharp I was a c-sharp developer like five years ago and I did a lot of stuff with generics and basically would do this and like inside of your code you would just be referencing the type as like T but you could say that that type extends a certain interface you can still do extra things in in c-sharp it's called a type parameter Hyuga says a type argument or a type variable okay that's good as a fun little tangent so this is a type argument so we're defining an action type that's going to take in the guestbook model type and it actually is not going to take in guestbook entry it's going to take in an array of guestbook entries so we're actually going to do guess both entry brackets like that so set entries takes an array of entries and does something with it so now in our implementation well we've already done it but set entries takes in the entries sets it on state our thunk here makes the API request and then sets the entries cool so easy enough now what we need to do is win the app loads up we need to make this initial call to our API to get all of the entries which will set it on state and show it in the UI so I'm gonna do that I think from the home view here so what we'll do in the home component is the first time the home component is loaded but is loaded it's gonna fire off the get entries action so let's do this so we're bringing in you store state we always we also want to do use store actions and now we can say get entries is use store actions with our state state that guestbook dot get entries so now that is in a variable and for this we're actually gonna use an effect so basically we only ever want to call this function once we only want to call it when the component is mounted and with hooks you do that in an effect and what you can say is here at the top of the component I'll say use effect you pass in a function and then what I'm gonna do is I'm gonna pass in an empty object is this an empty array is the second parameter and basically what this says is this effect has no dependencies meaning it should never run again it runs once and that's the only time we need it to run so the first time it runs we call get entries which will hit the API and then it will never run again unless this component is unmounted and remounted but if that's the case that's totally fine because I do want it to hit the API this is complaining because it wants me to put get entries as a dependency I don't want to do that so I'm gonna TS ignore it or maybe I need to ESL int ignore it what does it saying I need to es Lent ignore it because I just I want it to be an empty array because I only want this to every run once and that should do it so I'm gonna save that and now when the app loads up right here we can see in our redox dev tools that it fired off the action well and actually let's just do a complete and total complete and total refresh so refresh the page we can see that get entries gets fired off it has no arguments it's just calling the API and if we look at our back-end we see that there was a request for entries so that's good it got the entries back and it called set entries and we can see that the action just got called with an empty array because right now there are no irate there are no entries on our back in get entries success oh no sorry I think it did the initial set in trees the initial state and then because this is a funk it's asynchronous it starts then it's a success if we look at the state regardless there are no injuries anyways but ok the second once we start actually adding them there's it'll make a little more sense we can see it happening in there cool so that's great now we're going to update our add entry to actually call the API so instead of just pushing into the array it will call the API and then when it when that completes we will recall get in trees which is gonna show up in trees I'm tired I need to stop coding three minutes we'll finish this in three minutes so what I'm gonna do is I'm gonna change this add entry to actually be a thunk so now instead of just pushing into the array it's going to actually make an API request so if we go back to our implementation now this should be a thunk and this is an async function we shouldn't I swear three minutes we shouldn't have to set the IDE we don't have to set submitted because all of that's gonna be handled on the backend basically we just view this totally believe it well so we're gonna make a post request here so in this fetch we'll say method not that method is post mmm the you need to specify some headers the content type header is application JSON and we need to specify the body so the body is just going to be json stringify that entry that we just sent to this function so that's gonna make the post request to our back-end and then we're gonna get back a response and I guess technically we might actually get an entry for now I'm just gonna log it oh I'm overriding a variable um call it result like that so I don't think we'll have to change our components so if we look at a guestbook entry schema we can see that we call add entry and then we just reset the form but technically what we probably should do is show like a loading spinner whenever we click the submit button and then we should see it up here in the UI but for now let's just see what happens so now we're still calling that same action but instead of just pushing it into the array it actually calls the API like this so let's see what happens good work might work so it's profess the page looks fine in the console we can actually watch the redux dev tools we should see the add entry action get called or thunk its my name is CJ hello world this is my guestbook AB the entry and if we do look at the console we can see what we got back from the API look at that that's beautiful so what we what we technically could do is just my audio is delayed sorry I'm gonna leave soon anyways we could technically just take this array and put it into the into the entries array so let's do this let's create another action called let's call like push entry um no I got a better idea we're gonna rename this to be create entry because it's technically like creating it on the back end so let's let's rename it in our in our type so this is create entry and then we have an action which is not a func that's just called add entry which will add it to the array and this is a type guestbook entry cool and so now add entry it's very similar but it takes in an entry and then unshifted entries cool and so right here we can say state dot add entry and we'll pass in the result that should show it in the UI and watch this when I go back to the browser the paid the initial page load is gonna call the API and we should see oh we broke it one thing is now that our entries are actually coming back from the API entry dot submitted is just like a an ISO date string we could technically make it a string on the back end here's what we're gonna do on the back end we're just gonna make it a string so that way we're not trying to like parse it as a date on the front end and again this back end it's not a real back end it's just meant to demonstrate the fact that we can call an API from the front end is it a best practice to append your current entries or make a new array with the element appended well we're actually using easy peasy so easy peasy handles that for us so it may appear like we're modifying the array but under the hood easy peasy does a diff and then creates like fires off in action or like it dispatches a state update that is actually a new copy of the state with the new value inside of it but the way we write our code is just like overriding things or pushing your own shifting into an array and easy peasy takes care of turning it into an actual like react state update okay we want to go cow yeah I think that's fine um and then our JSON database we're just gonna empty this out so it starts back at nothing and then on our front end we're not gonna try to to string it we're just gonna show show when it was submitted like that and in our guestbook entry this is now a string it's no longer a date okay I think we've I think we've done it so page loads there's nothing my name is CJ hello world this is my guestbook add the entry it shows up it should have an ID but regardless if i refresh the page it doesn't show up what's happening um let me see the did we see any error in the console hmm look at the rejects dev tools well let's try it again oh I know why we changed the name of the action in the front end but we didn't update it to use the thunk instead of the action so in our in our guestbook we renamed this to create entry instead of add entry so our home component actually needs to call create entry not add entry sorry not our home component our form our form should be calling create entry instead of add entry that this is the winner this is what you've all been waiting for here we go no this is my guestbook at entry beautiful you can see create entry called and whoops cool and if we refresh the page it's still there so cuz when we refresh the page it calls the API and lists them out so now we have like sort of have persistence right we're gonna add Andrew in here yay let's see oh it ended up being lol not that that one okay that one that one add entry must be at least 10 characters start emoji like that awesome and if we look at the dev tools yeah yeah so no errors no errors in the console this is great and if we look at our like our simple back-end API it's actually just updating this JSON file I'm just totally fine but the point of this video was to show you a react app that's actually talking to an API so if we look in the store here get entries is a thunk it calls an API and we have that we call this an effect when the component first mounts and then we also have create entry which makes a post request it's all great so I can refresh the page all day long and on initial page requests it actually pulls those in from the API so let's do one thing let's let's do this instead of unshifted I'm actually going to push and then we can create a computed property this is the last thing I'm going to show you with with easy-peasy so now because I wanted it to appear at the top but then I realized the API order is it differently it was technically ten minutes instead of three minutes no the application is not hydrated from local storage the application makes a request to the API when when the page loads but okay so now add entry pushes but here's what we gonna do we're gonna have a computed property computed called reverse entries and this is a computed property that takes in the state and then just returns state dots light state dot entries dot slice dot reversed so it makes like a copy of the array and then reverses it and the cool thing about a computed property is this only ever gets recalculated if the array of entries ever changes so anytime we push into it this reverse entries no I'm not hydrated I need to drink you're right that's good water okay so now in our in her interface we need to implement reverse entries which is of type computed so this is computed with the guestbook model and I think it's it yeah like that so this should do it so now how would I update that kind of model to handle paginating billions of guestbook entries we would just keep track of the current page and I would still keep an array of entries we would have to deal with the API to do the pagination so the the API would have to expose like before or after or limit I would probably store all of those properties on my state like before after in limit and then anytime we call the API we use those those values yeah so no but computed properties are great we have these in view we've been using them for years but in react that are known as memorized functions and that's basically what we get here we get a function that will only ever rerun if entries changes so now in my component I'm going to use reverse entries instead of entries hmm and so now when we add a new entry it should appear at the top because that computed property will rerun right now it's complaining because it's saying entry has a in any type I wonder if we define the return type like this like array of guestbook entry does that do it I need to look up the computed ducks store models computed typescript API computed so wait how do we define it in our interface though computed model result store model you the model against which the computer property is being defined yeah so I think I have that right that is guestbook model and then the result is the type of the derived data that will be returned from my computed property so my computed property is returning an array of guestbook entry so I think that's right I think typescript just needs to catch up yeah there we go touch you're just needed to catch up and thank you for the follow couldest zebra I hope you get warm cold a zebra and zoo bear says just joined what is easy peasy and do we are are we using redux as easy peasy consists of function actions no so easy peasy is like a way of managing global state in your react application it's a replacement for redux it uses hooks by default it has a an interesting way of updating state and one of the things that I like about it so typically with react state management libraries you have to create a copy of the state and then update the copy but with easy peasy you just modify it directly and it takes care of figuring out what changed creating a new copy and then applying applying that and with these these thunks and these actions that we've created that are just simple functions here they automatically get registered in the redux dev tools so if we look at redux we can see that get entries was called set entries was called if I add an entry here for Zubair Wow easy peasy is so easy is there a PMO gee I don't think there is I think there's a green dot emoji green heart add entry so when you call add entry that actually makes an API request and so this is a thunk to create entry and then once it was successful it actually added it to the UI and we're seeing that our computed property works as well so these are in reverse order so it made a post request to my API and if i refresh the page on page loaded we call the API so the data is still there very cool very cool technically it was 15 minutes instead of three but we did a lot more than I said we were going to we I introduced you to computed properties this is cool tell me computed properties aren't cool these are cool all right I think I'm done for today no pee emoji utf-8 is literally usable I agree I totally agree all right I think I'm gonna go this was fun I think I covered all the things I wanted to cover let me just look at the title of this twitch stream because I think that had all the things did you just add quick is it gonna pop up like every minute so we have react we have typescript we have hooks we have react router we have material UI we have easy peasy and we have react quick form yeah so some things you might have missed if you have you tuned in later is we added form validation which is cool so we're using react hook form but we have validations so if they're not filled in we show show errors we have actions and it's it's a beautiful thing we did a good thing here when one thing that's cool to point out is because we have this global store actually don't have any props in any of my components in a larger app you probably still have props but in this case our home component can just it just gets access to the entries and it's always gonna have the latest array of entries and then our inch our guestbook entry form calls create entry which in turn updates the array of entries which in turn rear Enders this component so it's a beautiful thing the most over-engineered slick guest books of mercy Thank You doc thank you so much much appreciated class name is a prop I guess that's true and hello Brandon who says this has been super awesome even though I live react and have done several projects and know a lot of this stuff it's been super helpful lots of fun you did a great job Thank You Brandon I appreciate that now back to view JK this is very informative cool we got to use typescript though that's a thing what actually what I what I do want to do is to take this application that we built and create an actual tutorial out of it so this was in total five and a half hours of me talking to chat and breaking things and and all that but we can take the fruits of our labor and turn it into like a 30 40 minute tutorial I don't know maybe we'll do that at some point soon cool so I think that's it thanks everyone for watching not love not live okay love react I see I think they could mean the same thing like you write react on a daily basis alright let's find somebody to raid and then we're gonna get on out of here looks like Sica player's life they're learning view j/s that'd be a change of pace right oh he's a mastermind live yeah that's where he best remind they keep ready that's before their coding and go fizzbuzz and go alright we're good we got a raid mastermind so if you're watching on youtube head on over to twitch and we're gonna do a good old-fashioned rate first real quick shout out to Shawn our latest YouTube member I'm going to show all the members and YouTube sorry members and patreon patrons on the on the screen so Cody garden is brought to you by viewers like you like like these people here a goodnight client telephone and thanks for hanging out see you later doc I will try to enjoy my TV shows the Promethean now we're gonna raid mastermind day oh he's rated us before and they're doing cool things and there Shawn the latest avocado on YouTube let's appreciate it alrighty yeah so we got the raid message ready be sure to copy and paste that raid message make sure we read in the right way there we go getting ready to read alright everyone wherever you are in the world have a wonderful morning afternoon evening or night and we're gonna just let let this finish really quick so you get it you get a few more seconds of CJ there's there's a lot of people there's a lot of people the Reid timer might actually run out oh there they are okay Oh buddy all right wherever you are the world have a wonderful morning afternoon and evening or night until next time here's this [Music] you
Info
Channel: Coding Garden
Views: 6,476
Rating: 4.8759689 out of 5
Keywords: full stack web development, learn node.js, beginner, coding, tutorial, lesson, full stack javascript, news, html, educational, learn javascript, learning, qa, live coding, live stream, web development, full stack, node.js, javascript, css, backend, frontend, mechanical keyboard, web, live streaming, programming, debugging, vscode, q&a
Id: Y1Y6s2kEUKs
Channel Id: undefined
Length: 139min 54sec (8394 seconds)
Published: Tue Jan 14 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.