Watch on YouTubeThe player loads when you press play.

In this talk

In the live demo I use a GraphQL query to ask for the fields the client needs, describe their shape with TypeScript, and read the result in a React component. I use hooks to connect the pieces, show a loading state, render a list, and update its data.

I also included an “anti-pitch”. The tools add complexity, and I wanted developers to be able to decide whether that cost made sense for their app and team.

I gave this talk at DevConf Live 2020. The date at the top is when the recording came out.

Read the automatic transcript

YouTube generated these captions and sometimes gets names, punctuation, and code wrong. Check the recording if something reads oddly.

0:00 — hey everyone my name is Jacque and I've been working with computers ever since I can remember this is me when I was just a few years old and when I was 11 I first played around with basic HTML and JavaScript and then later moved on to the hottest tech of the day PHP and I remember finding it pretty magical that you can have a server generate and serve a dynamic HTML page and that you could interact with it by submitting forms and

0:31 — passing query parameters but I think it's safe to say that the web has come a long way since then I now work at names and faces as a senior full stack engineer and at names and faces we solve a problem experienced by everyone from the CEO to the intern how do I get to know the people around me how do I get context for where they fit in and how do I get in touch when I need to and we do this by offering a world class employee directory available on web and as a mobile app and we're backed by Y Combinator and Excel Ventures and we've already got over 150 companies to use

1:03 — our product our current business model and systems are built around onboarding clients individually select kind of an enterprise sales model and service model so typically a potential client would reach out to us or we would reach out to them and we'd go through a manual sales process and would set up the clients directory for them but our goal has always been to move to self-serve model where anyone could visit the names and faces website sign up and have a basic directory up and running in five minutes and this would allow us to scale and make our directories available to anyone not just companies so after going

1:35 — through Y Combinator and being funded we decided to finally do it so we had to make a decision do we extend our current tech infrastructure to accommodate a self-serve model or do we use this as an opportunity to start fresh and we chose to start fresh for a few reasons so firstly our current tech is built around the enterprise sales and service model so it's got some super complex logic for custom setups and our current tech is pretty much existed since the beginning of the company and while the tech is very sound it wasn't necessarily built with team scale and flexibility in front

2:05 — of mine because you know in the early stages of the startup when uncertainty is high the most important priority is usually features up the Dormouse right but we wanted a clean slate so we could rebuild our tech with different goals in mind namely we wanted to build code that scales with time and scales across a growing team and growing feature sip this was especially relevant because we were about to increase our dev team from a team of three to a team of eight and we also wanted to build code that allows us to iterate fast our code shouldn't stop us from experimenting because we

2:35 — didn't know exactly what a self-serve names and faces would look like and finally we wanted to reduce user facing bugs and errors and we also felt that better technologies now existed that could help us accomplish these goals and my inner developer was pretty chuffed about this because it meant that I had a couple of weeks all to myself playing with and evaluating a bunch of exciting technologies and helped decide which ones to go for that kind of sounds like developer heaven to me and after a couple of weeks of experimenting and evaluating we ended up choosing Reax

3:07 — typescript and graph QL as the core foundational technologies for our new fronting and now that I've worked with these technologies for almost a year and react for much longer than that I wanted to share how they work I'm not just how they've alcott helped us but how they can help development scenes of any kind rapidly build and scale the front ends now I can appreciate that different teams have their own unique challenges and situations not everyone gets to start fresh like we did but I don't think it matters whether you have an existing project or whether you plan to

3:37 — adopt just one of the technologies I'll be chatting about I mean even if you don't end up using any of this check it all there are still some great concepts and patterns that can translate to other technologies and even technologies that live outside the fronton world and of course there are upsides and downsides to these technologies and they might not fit everyone but we'll get to that a bit later but my only hope is that you walk away from the session with more insight into these technologies and the reasons they can be so powerful so for our new front end we ended up staying with Reax

4:09 — which we use in our current system and we're very happy with it react is a JavaScript library for building user interfaces it's maintained by Facebook and according to the stack overflow developer survey is the most framework and what sets react apart is that it's super lightweight and that's why to hold it library another framework it focuses on one thing and that's building your UI right it provides an API to you to declaratively describe your UI and then renders that UI efficiently and reliably and it doesn't

4:40 — care how you manage your state or how you route users around that's all up to you your react code base is made up of various components that are composed of all your UI on the left here you can see that we have some components that we wrote ourselves a heading component to the modal component these aren't actual components in our code base just some examples and on the right are two other examples of components but you can think of you can imagine that these might be imported from a library so the one is a date picker that might render like a

5:10 — calendar or you can click on a date and that will give us a date back and we can then log it out or do whatever we want with it and the other is a route component that forms part of a routing package and you might think this looks an awful lot like HTML and you aren't wrong this is react way of using your components and it's a language called JSX so JSX is JavaScript but with an XML syntax on top of it and it gives us an ergonomic and like logical way to use stack and compose our components so for

5:41 — example without knowing JSX i'm pretty sure you can assume that the div that contains hello world that we've passed into our modal is going to show up in the modal because that's how it works in HTML right and we have a logical hierarchy of like composition where you can you can see that the div is inside the modal because it's wrapped in it and it's indented and that's what makes xml and HTML so great right and the other powerful parts of JSX is that it's just JavaScript plus a bit more meaning you have the full feature

6:13 — set of JavaScript in your J's X file and we're gonna have a look just now around how that's how that looks and works but the idea is that instead of separating your logic and marker by separating the tip used to build them your rather separate your concerns and keep your logic and mark up together so here's an example in angular so for a single component in angular you separates out the code by what technology that part of the codes regiment right you have your business logic in one file your template in another and your styling in another but in react everything is written in

6:44 — JavaScript for our button component we declare the business logic the markup and the styling in a single file and this is great because it encourages you to think about separating parts of your code according to what it's responsible for and not according to the technology it's resonant and this is how you define a component in react it's just a function like you can see here we have a function called button and it takes in parameters and react calls these props in this case we're pulling an on click and label we're taking that in and we're

7:15 — returning a react element so you might have a few questions by this point the first is what happens to the JSX before it hits the browser surely that browser can understand you know HTM like an XML like syntax merged into JavaScript well your Isaac can't but it's actually just a very light light layer on top of JavaScript these J's X calls so you can see this is apart from our previous component and that just gets transformed into a JavaScript function call and that is returned tomorrow from our button

7:46 — component and the other question you may be asking is when does react call your component function like when is this actual button called right and what happens when your it's like what happens to the elements that you returned from your component well you can see here that when our component is first rendered we use our component in JSX and let's say we pass in an open modal label to it right what happens is react transpires that ax transforms that into a JavaScript function call so you

8:16 — can see that we call react our create elements which creates which and the first argument there is the name of the HTML elements you create which is button in this case you can also pass in if you're rendering a react component that would actually be the component instance but we'll get to that in a second and the second argument are your properties or your arguments for that for that element so in this case it's on click and thirdly it's what you're passing in as Joel

8:46 — written to your component in this case it's a string that just says open modal and then react creates the element for us in the Dom see here you can see in our third step we have to actually interact with the browser and tells it create this element put it inside this other element set it in a text to whatever we passed in and add an event listener but then if we pass through a new label on our second render so we pass up we call our button components again with a different label prop you can see that it goes through the first

9:16 — two steps in the same way but in the third step all it does is it figures out what changes need to be made in the Dom in the browser and it only makes those changes so here you can see it only sets the inner text for that Dom element and it knows which elements you to affect because it stores a reference on first render and this is what makes react so great you can describe your components in a declarative way and then your whole render function is rerun meaning you don't need to number one figure out which part of your components are you

9:47 — run because it just all runs and number two you don't have to use the Dom's imperative API to build your UI right you don't have to go document or create elements button etc you know if you use methods like document or create element or element in a text it would be your responsibility to figure out what to change but react does this for us you know we can focus on describing on UI rather than figuring out what which Dom methods to call and making calls to the DOM is slow and it's a blocking operation but because it Optima because

10:19 — react optimizes calls the Dom is actually very fast and just a side note a react component also rear Enders when its internal state changes but obviously I showed you react component and it's just a function and you might think that you might wonder how a function has state well functions in react kind of have States and we'll touch on that real soon but we chose to stay with react because it's proven itself to be a scalable way to build you guys it naturally encourages separation of concerns you know you break up your code according to what it does and what its

10:49 — responsible for and we can build out all of these components that can operate independently of each other and we can fit flexibly compose them depending on the UI we need to build not only does this mean we can reuse more code but we can also easily remove code if we don't need it anymore we simply delete the components and all users of it and the code also scales well across the team because developers can use a component written by someone else without having to dive deep into the component code the component has a clear the eye of inputs and output and because it is so lightweight and

11:20 — interoperable we had the freedom to choose how he would do data fetching authentication routing and more we like we weren't tied to any specific frameworks way of doing things and this is one of reactor core principles all it does is provide a common abstraction for building a UI and the rest is up to you one of our existing code was written using plain JavaScript and for our new system we decided to make the move to typescript so a quick intro so you type script it's a strict superset of JavaScript so any valid JavaScript is

11:50 — valid typescript so if you take any snippet of JavaScript pop it in a typescript file it'll run just fine so you can kind of think of it as JavaScript plus some extra stuff and that extra stuff is static type annotations and this means we can describe the structure of our code and data in a way that allows the typescript type checker to alert us of any possible runtime exception exceptions but instead of alerting us at runtime we get a load of compile time so instead of either error happening at runtime meaning our

12:20 — users output break we can catch them at compile time before these bugs even hit production and I'm sure a lot of you have seen this error before cannot read property X or undefined if you are a JavaScript developer you definitely know this and as a J's developer probably the most common and most annoying area you need to deal with and it's because JavaScript doesn't have static types right anytime you access properties on an object you have to be very sure about the structure of that object so if I go if I have an object and I have a property on it called example and I go

12:50 — object I'll example but that object is undefined I'm gonna get this error but because we type our objects in typescript and all of our other variables we don't have that worry you know you can think of type scripts static types as a very sophisticated code linter kind of like ear Slynt or code checker which you helped belong by defining types but the bottom line is that type stuff isn't a wildly different language to JavaScript that it's rather a thin layer on top of it with tooling around it in fact if he stripped out all the typescript type definitions from a

13:22 — touchwood file the code would be a hundred percent valid JavaScript and in fact this is one of the reasons we chose typescript it's no different to the code we've been writing for years the only overhead to learning is the additional type system we we also wanted a way to make it easier for anyone on the team to understand any part of the code and type strip helps us immensely with us because types are a form of API documentation right without JavaScript code for example you often don't know what it passed into a function what you're going to get back without diving into the function itself and looking at all the

13:53 — uses of the arguments and all the different code paths and returns so types Tripp helps us fulfill our goal of a scalable code base right that checks our one goal we also chose it because we were getting a lot of runtime exceptions especially a lot of cannot read proper TX of undefined errors and this has helped us dramatically cut down on on those runtime errors again check lastly we wanted our code to be flexible to change without us breaking things when I work on our own system today I only now realize how much extra work I have to do manually following code execution to

14:25 — make sure my change didn't break anything and this is true of all complex JavaScript projects out there I'm sure again another check you decided to use broth ql as our api layer as opposed to our express powered rest api that we have in the old system and a quick intro to graft y'all it's basically it's an alternative to rest and it's nothing more than an open specification that describes how the client and server communicate and although it's just a spec there are a ton of tools around it including a company called apollo which

14:55 — builds boards a ton of tools and i'll get to that a bit later but how it works is really simple first you define the structure of objects you want to query so here you can see we have a to do type and it's got two fields on it the one is an integer the other is a string and then we have a user type with an integer two strings so email and name are strings and a user also has an array of to-do items so you can reference one type in another and then finally we have our query type at the bottom where we say that if you

15:27 — you're gonna get a user back second you query the data you need right so this is an example here in the middle of a graph QL query so we're saying that we want a user that could return the current user I'm not sure exactly how this API is structured there just an example obviously but let's say we want to query a user and we want the email address back and then we also want an array of all their to dues but just the label so thirdly you receive an object in the same structure that you requested so here we're getting check that looks

16:00 — exactly the same as our up query I mean so we can predict exactly what what the structure of the data is it's going to come back so your API structure is defined using what graph Cal calls an SD L or schema definition language and this is just a document that describes what can be queried from your server and the structure of the objects that can be sent to it and returned from it so your graphical API by design is strongly typed and self-documenting because the entire API structures already written

16:30 — out and this ticked the boxes of our three goals it's scalable because it's self documenting we no longer have to go trawling through server-side code to figure out how to interact with the API and it allows us to rapidly iterate and it reduces bugs because it's strong typing gives us great developer tooling like auto complete the graph child playground which I'll show you guys soon and develop and compile time error check but I find it's hard to get a proper sense for a tic without seeing it in action so let's build something tangible

17:01 — using reacts type script and Raffaele so to do so let's pretend for a few minutes let's pretend we're a developer working for a start-up that's holding it to do the stat so after spending most of our funding on stocking our kitchen with Soylent and protein bars as startups do it's time to put the rest of the funding to good use and get our app launched so we've broken the app up into various JIRA tickets to allow our team of six to work on parts of the app simultaneously so we're gonna pick up the next ticket and our ticket is now to assemble all of

17:32 — the different build components into the final app and hook it up to the server so I'm gonna start by just heading into my IDE so got my IDE over here on the left and what I just need to do quickly is reset things and this is why live demos are terrible because they're always going wrong so let's exit Zen mode in yes code and just undo all the changes we made stub it back to a clean slate and that was my last minute practicing so we have our

18:03 — app here on the left and on the right here we have our actual app DesPlaines we have a vs code on the Left which is if for those of you don't know it is Microsoft's fantastic IDE that is partly written in typescript and it's what a complete engine is powered by typescript which you can image we're going to see an action in a second and then on the right here we just have a little react app up and running so if I make a change here and I make i refresh on the right so you can see that my change pops pops

18:33 — up over here so our first task for this ticket is to add our user components at the top so let's do that so I'm gonna put in our user component and you can see that typescript actually automatically imported our user component because well I'd rather I should say vs code did it but in the background I should have did it because typescript knows our project structure and it knows all of the variables declared that I exported as modules so I get my autocomplete it pulls it in correctly from the right path and you can see that we now have our user

19:03 — component brought in but if when the app reloads you can see that we actually get an error and it's saying property name is missing in type but it's required in the user props type so you can see the red line underneath my component as well and that's because the developer who wrote this component added prop types to it so if we go into the component we can actually have a look at those and we can see that here's our type which is just a typescript type that we pass into our

19:33 — component and it just says that we have one property called name and it's type as a string right we can see it here as well if I open up my autocomplete which is another vs code feature part powered by typescript you can see that our name property comes in here and we can ignore these two just because they're specific react properties that we won't we won't touch them but again reacts word for a parameter is basically a prop right so what's really cool about this is you

20:04 — know it's one of the most impactful effects of tightrope being able to efficiently and automatically share knowledge across teams organic rattling across developers in a team so without needing to look at the file itself I've been able to see how to use this user component and and and my build obviously won't pass if I don't use this component correctly and obviously I didn't write this component you know someone else wrote it and I have no idea how to use it until I actually look at the types and if we didn't have the types I'd have to dive into the into the code

20:34 — to see what's happening or someone would have had to write a manual documentation you know normally I'd have to go into the code a figure out which props can be passed to figure out which ones I need to pass but with typescript it's easily discoverable it gives me autocomplete and the correct use is enforced in our CI and I cannot merge my PR if I have a type error right so that's how we have it set up on our side is when a PR it goes in two to get hug we have a hook that fires off that runs type checking and we'll come back with an error if our type of our type

21:06 — checking failed which is really great and that has eliminated a lot of runtime errors in our apps so we need to pass in a name obviously so I've got my autocomplete and I'm just gonna put some random string in here for now but and that looks good right it's surrendering out so user component but we actually want to fetch some data from from the API so I have my API running locally and I can open up the graph key I'll playground which is served by our API and I can go ahead and look at the docs

21:37 — section of growth of our playground and this is our API documentation so just by building our API in graph QL and assembling the schema definition language that can be pulled out into some documentation and this is a lovely interface for us to explore what a API can do right and I see I have one query available to me which allows me to fetch a user and if we were using a REST API now without any documentation like tooling like swagger I need to troll through the code to find the right end points and once I find it I need to

22:08 — figure out the parameters to faster than all the possible return values and response codes but with graph QL you know exactly what you need to pass in and what you're gonna get back I can write the query here in the playground with because it has the benefit of autocomplete but I actually have an extension installed in vs code that gives me Auto completes right in beers code and obviously my query is going to end up in my code anyway so might as well write together right so let's create our query let's call it user data

22:38 — and I'm gonna use this gql tag which again is water important thanks to typescript and this basically just tells Tut is a marker in our code that's anything in this string is graft yard so I'm going to create a query I can call it whatever I want it's just a label for this specific berry and you can see that again I have autocompletes so I have I have to graph kit like internal graph QL queries yeah the one is schema and if I actually query in schema I'd get my whole API schema back which is quite

23:08 — cool but I want my user right so if I select my user you can see that automatically gets the any required parameters filled in so I need to pass something in to where and you can see that I need to pass in either email or ID into the where clause so let's do ID 1 and just a note here this might look like I'm kind of writing something similar to a MongoDB query or a sequel query but this is just how our graphical API is desired right it's complete graph

23:38 — TR isn't a direct interface to your database it's rather it's rather and and it's rather spec that you can use to set up your API to work best for the front-end I kind of feel like the REST API is are optimized for the server but graph QL api's are optimized for the front-end right you just you you can structure your graphical API and however you want that works best for your and front-end no matter how your database is structured so if we rather if we didn't want this where clause because obviously it's insecure because I can just change the ID that I fetch the user for but

24:09 — obviously it's just an example I can just have a current user query which will just fetch my current teaser for me I can just call it use if I wanted so I can do whatever I want right even though it might look more like a query to the database then rest would be it's it's it's completely up to you how you want to structure it right regardless of all of your DB anyway so what I need to do now is I need to select from my user object which fields I want back and for now I just want name

24:40 — but you can see again we get out all to compete so let's pull that in and now we have our query which is really cool and you can and so with gravity all we need to specify what we get back because by default nothing nothing comes back in fact it's invalid so just do not it's invalid to not specify what you want back and what's great about that is you can then choose just the fields that you need for your UI meaning you reduce the response payload from the server and any additional work on the server to fetch related data or whatever so now we can

25:12 — we can integrate graph QL and reacts and actually fetch this data and pull it into our component and we can do that through what react calls hook so let's import a used query hook and we're going to pass our query in here and you'll see that the response we get from this used query hook gives us the state of the state of our query so data loading and error we can remote F and I I'm not going to do any error handling but basically hooks allow you to add

25:45 — additional functionality to your components and what's really cool about hooks is they allow us to add state to our react components meaning that this used query hook can cause this app component to rerun so when this used query hook gets data back from the server right then loading this this function is gonna run again but the result here is gonna be some new variables so instead of loading being true so so actually let me just log it out and we can have a look at that so if

26:15 — I log out data and loading right and obviously for every line that we love that we will see a log for is the componentry running right so you can see that here we go here's all the different runs of the component and you can see that the first run of the component data is undefined and loading is true but as soon as the data has loaded this whole functionary runs again data is our data and loading as false so that's how you can add stateful logic to your react components and it's

26:45 — a very simple way of doing it because there's no mutation involved whenever the state changes in your react component everything reruns and you just get new variables within this closure so let's add a loading state so I'm going to say if we don't have any data or we're busy loading I'm just gonna return a dev and just a loading and again you can see the power of react here you can see that I get by the virtue of you know by virtue of just using JavaScript logic I can rinse out different like code parts here that I return and it'll

27:16 — return different react elements and depending on what's returned from here react is gonna add remove Dom elements for me automatically right so now I can actually take my data and pass it in to name so if I go data dot I'd expect to get some autocomplete right that'd be really nice but if I hover over data you can see that data is actually typed as any which is type scripts type full this can be anything right and that's because tightrope doesn't know what the

27:47 — structure of the data is that's gonna come back from this news query but what we can do is we can use a tool called cogent to take out graph QL types because graph kills statically typed and pull it into our type script for us right so I can run Y on cogent and what it's going to do is it's gonna create a new file for me so if I import a user data which is a type and pass it to my use query hook you can see that my data type is now defined it as user data and if I if I head in to look at what user

28:17 — data looks like user data is an object with a key of user and that user is another object that has a name field that is typed as a string which is in line with what we get back from graph QR so now if I go data dot you can see that we have we get data dot user dot name fantastic autocomplete and again error checking if I don't pass if I don't have the right code so now we have shared types between our server on

28:48 — our client which is super super cool next we need to display the list of to do so let's import our list component let's do that quickly and our this component again is just a generic components that can render anything it can render any content and it's let's say it's built into our UI library right so we need to pass a couple things we need to pass while a couple crops data and render item let's pass through data and data if I hover over it you can see that it's an array of some unknown type

29:19 — so let's make it an array of strings because just to test our list I'm just gonna render out this array of strings right and then for my render item prot I need to pass in a function and that function gives me one item and that item basically based on that item I need to return a react element for for that given item and it'll the list will then take this element and put it into the list for us right so this function over

29:50 — here is going to run for each item in this array and it's gonna take the element that's returned from it and put it into the list and you'll notice if I hover over item here it's typed as a string and that is because I passed in an array of strings and this is one of the most powerful features of typescript its typescript generics you can think of them as parameters that you pass in two types with inference meaning if I pass if I type this list correctly I can type

30:20 — it so that whatever I pass in here as an array this type over here is a single item from that array right no matter what kind of thing I pass them here which allows your types to be very very flexible so let's actually pull an r2 dues for now I've just returned a for now I'll just returned a dev that's just it's from the red router item let me just open up my chat here it

30:51 — seems like there are a few there are a few questions which I'll quickly jump to someone's asking how would you Mach graph QL queries ingest answer to that is there is tooling around that you can mock them there is a special mock provider that a product gives you so just a bit of background on Apollo with graph QL Sao Paulo is a company that offers a full graph yell tool chain there the the leader the industry leaders so they provide a client API which were using

31:23 — now with this music where you hook and with and they also up to write a server which is really cool and they provide the cogent tool and they provide this vs code extension yeah and then so I'm going to continue with a demo for a little bit more and then head to head to some more questions at the end but please keep them coming cool so I've got my dev rendered here for each item but we actually want a fair try to do items so what we want to

31:53 — do is fetch to do items for this specific user right so normally with rest we've got two options one is we can add the users to dues to the user endpoint so when you fetch the user with risks you just get the user parts back plus two dues but that means you need to either do that yourself or wait for dev to do it back in bed to Bert it also means you to fit over fetching data right if you have a user query and you fetch all the users to dues and return that as well all the places where you're already using the user the user endpoint or where you might use it where

32:23 — you don't need those two dues that data is going to be a fetched and returned unnecessarily right you can always add a parameter to condition you return it but that just becomes a mess the second option is you can make a another API call to just fetch two dues but that means two API calls and you may have to do the calls in series if the two dues endpoint depends on the result of the user in right so if I had to if I've only got the user ID from my first endpoint and my second endpoint needed that user ID I I would have to wait for

32:55 — the one endpoint to finish responding and then but with graph QL we can map out our data relationships so if an object has a seduce field so object has a deduce field right meaning we can fetch to dues for a user and we can see again we have autocomplete so I'm gonna Fitch I need actually donate ID so let's just fetch label and complete actually I might I do need ID later ID label and complete for

33:26 — our two dudes right now I can simply run code gen again and starting in my array of strings here I can go data dot user dot and I now have my two dues object as well because of cogent so now I've passed in my array of two dues and if I hover over item you can see that the type is a single to-do item so if I'm just going to rename it it to do for clarity and a final go to do dot I get the fields that I queried on graph Kyung

33:56 — which is super awesome so that's a combination of graph GL cogent and typescript generics all working together to give me a really great developer experience so now we can import our item components which represents all weight which is used to render is specific to do item and what do we need to pass in well we need to pass incomplete label and unclick so let's do that to do doc complete label will be to do label and unclick will be just empty for now but

34:30 — we are going to add some interactivity later on but now you can see that our two days are rendering out just fine which is awesome alrighty so now we have our to-do items render up rendered out now that we have that lets add some interactivity so we want to mark the to-do item as complete or as incomplete when clicking on it so reflecting data updates has evolved a great deal since static pages in the beginning we had static pages with forms right which posted to an endpoint so you'd fill in a form or you'd have like some sort of UI

35:02 — that's disguised as an HTML form that would submit an API the page would reload and you to fetch all at your updated data but everything else is well right but nowadays what we do is we add custom state logic front end to hold on to data from the API right so in react this means using a state management library like Redux so we would make an API request copy that data into our client-side store and provide it to our components and when we make an update we listen for the API response and then we update the local

35:32 — state to match the state of the API and often this leads to a lot of API logic that needs to be duplicated on the client and needs to be kept up to date if API changes and Apollo provides a similar solution but one that's way more ergonomic can automate it so let's let's see how this works so I'm gonna head back to our graph Gale playground and you can see that I not only have queries but I have mutations and mutations are basically you can kind of think of them as similar to put or a post or a delete in rest so it's basically anything that if you call it will change something on

36:04 — the server side right so here we have one that's called update to do and I'm just gonna go ahead and use that in in my in my code over here so let's call our mutation update to do and again it's gonna be the graph QL operation and we're gonna say this time that it's mutation and we can call it update to do and we're gonna use the updates to do mutation and you can see that we have C required parameters here the first is gonna be data so what we want to update

36:34 — so we're gonna want to toggle the completes value right so I'm gonna pull that in and we want to update is specific to do so where the ID is whatever ID again you don't have to structure your graph here like this this looks very much like a DB again but it you don't have to make it look this way if you don't want to you can do whatever is best for your front-end right and then with our mutation we're gonna take in some variables pass them through JavaScript so the one is gonna be the ID

37:04 — which is an integer and it's required which is why I have this and the second is gonna be complete which will be a boolean and required again that's spelling right cool now we can pass we can we can choose what we want to get back from this mutation I'm gonna get back ID and pleat and the reason we need to specify what we get back from this mutation is because our mutation returns our updated

37:36 — to do object so we're gonna tell it my toggle like mark I'll to do as complete or not complete and mark this specific stood for this ID and return to do I to the to do ID and to do complete and you'll see how we'll use that in just a sec so now we're gonna use another reactor called News mutation and I'm gonna pass in my mutation and again I can run cogent which is really cool

38:06 — so I'm gonna run cogent and let's pass in my cogent type and now I have two types that I can pass in the one is update to do and the other one is update to do variables because we have some variables that we're passing into a mutation we have this type now as well and this hook gives us back a function that we can call to actually action this mutation so let's do that so let's call our function updates to do and this update to do function we can just call

38:36 — it from our unclick so let's do that so that's called update to do and obviously we need to pass in variables and if I if I save here you'll see that I actually get an error saying that this empty object is missing ID and complete because we set our variables is required that's trickled through to typescript and we're getting a typescript error again meaning that if we put this out as a PR we would get a bold fail yet wouldn't be able to merge the next pass in our ID which is going to be able to

39:06 — do ID from for this given to do right so we're just taking this to do item and getting its ID and then we're gonna set the complete value see the opposites of what it currently is right so if it's currently complete so if this is true it's gonna flip over to false and vice versa now if I save this you can see my error goes away because I'm passing the right types in and now when I click I when I click this mutation runs and

39:36 — interestingly enough not only does the mutation run but our data comes back from our query over here gets updated with the new complete value so even though I'm running my mutation which is that we can we can trace this right so firstly I run my mutation right that goes to the server and that says ok set this to do is about a complete value to the specific the specific new complete value and we can see what that looks like right so let's head into the

40:06 — network tab here this might be a bit tough with a small screen but let's see so you can see that I tell it I give it my mutation and the response is my to do so the ID and the complete but updated to do object right and what Apollo is smart enough to do is it knows that we've just come back with a to-do item because this type name is included so it knows that these fields reference a

40:36 — to-do item and it knows that this is our unique identifier for that item so what it does is it takes any other fields like complete or whatever else we might have changed and it updates our local cache automatically so any queries that reference this to do we'll get the new updated complete value so we don't even have to worry about when we get the API response back we need to change our local states to update the complete value so there's no duplication of client-side logic there are a few cases where you do need to do some manual work

41:07 — but for the most part everything just works automatically right it's almost it's kind of like two-way data-binding but it's it's done in quite a functional way so that is our that is basically how a graph queries and mutations work and how it integrates with typescript and react there are there are some other great features to all these technologies but this is pretty much the end of the demo but it was just a high-level

41:38 — overview of the tick and there is much more to each of them that I could fit into this talk so I encourage you all to dive deeper and if this felt like a bit of a sales pitch it's kind of because it is because I wanted to reflect on our positive experiences with using technologies and how they've enabled us to build UI faster than before but as with all technologies you know it's you know it's that they all have their downsides right so now it's time for the anti pitch and there are a few reasons

42:08 — why you might argue against adopting these technologies the first one is the overhead of learning these technologies right this is tiny valid there's always an overhead when incorporating new tech into a dev team and it's something you need to consider depending on your situation but in my experience they're all relatively easy to pick up especially react in typescript because of how similar they are to the technologies they've got on top of four of the new developers we hired at names and faces last year came from a Ruby on Rails background and they had mostly worked on backends with and within a

42:39 — couple of months of working with this tech they were fully comfortable with it the second is adoption over the head write all of your code may be written in completely different technology so you may feel like you have to rewrite everything to adopt them and get the benefits of the office tech and that's not usually an option that makes sense for you right you could have spent years investing in your current tech and you don't to just throw it all the way but thankfully all of these technologies are interoperable with other tools and our incrementally adoptable react is fully

43:09 — interoperable with other front-end tech so you can start by writing only a few new features of your app with react if you want to and it's also got escape hatches to do low level like imperative Dom operations this also allows you to put non react components inside react so if you know if you were brave enough to wrap a jQuery UI datepicker as a react component you could and type scripts or synchro incrementally adoptable right you can set up your project to allow plain JavaScript files meaning you can keep all your existing

43:40 — code in typescript or you can keep all of your existing JavaScript code and then add type scripts when you write new code so the benefit you'll get here from typescript will increase linearly with the percentage of typed files in your codebase so you'll get benefits from day one because you'll have your title project set up your JavaScript still working as is but because you start from then on to writer we write the new things and types you'll get the benefits and slowly you can migrate things over and graph girls

44:12 — also incrementing adaptable you know you can use it for new features only but there are even tools where you can proxy your REST API through graph QL if you want to do a slower migration or if you just want to use graph QL and want to keep the REST API going but I hope my overview today is giving you a better idea of how these technologies work and what they can do and how they can accelerate front-end development and what an adoption path might look like if you're interested in learning more check out the relevant reactor type script and graph GL websites they all have

44:42 — fantastic documentation I don't think I've ever seen better documentation than the react Docs and I'll also be writing a blog post based on this talk with some more info and nuance I might split it up into various parts so look out for that by following me on Twitter and lastly yeah visit names and faces com if you want to learn a bit more about what we do and if anyone has any other questions now feel free to ask them let me have a quick look yeah cool

45:15 — are there any specific extensions for vs code that you highly recommend for someone working with a stack yes there are a ton let me let me open up my let's see what I've got actually I can't quite remember what I have but let's do this quickly there we go so have a look at my extensions so I've got the Apollo graph QL extension like I mentioned this gives you syntax highlighting and autocomplete like I showed we've got a few other things related to our a few other things

45:46 — like darker because we use darker file of containerization but then yes lint is great as well obviously it's a tool but it's also he has code extension so it catches any oddities in your code that something like typescript might not even pick up i've got prettier which is fantastic for JavaScript and graph QL so you can see obviously that I had quite a small vs code window and what I told prettier was that if I have a really long line it just means to collapse it

46:17 — for me so prettier is really great and that's pretty much what I would I have vs code-wise but there are a ton of other extensions I always just look at the rating and if it's a good rating and got high usage then yeah then I would I would just install it what would you recommend angular developers to start if they're interested in switching to react to prepare for a role with this stack honestly I would go for the reactive documentation so let's quickly head

46:48 — there so if I go to sorry I'll show you my browser history though for a second this stops search so the react documentation is great they've got a tutorial for building something in react so if you like going through a tutorial go for that it's amazing but if you like learning from a more technical side but still obviously in an incremental and not overwhelming way you can check out their main concepts series of posts and

47:18 — this introduces you to react slowly and incrementally which is really great how does use craze set the internal states I thought it would need to call set States correct yes it's it calls set states but it uses the used state hook so I can quickly show you how this works if you'd like let's open up vs code real quick and let's get it into where we had it and

47:48 — get into Zen mode there we go so for those of you haven't worked with react state before there's a hook called use state which is built-in to react and let's have it initialize it's the default value at 0 again I'm gonna imported automatically I get so the question basically was around how how does how does this trigger our actual

48:20 — components you rerun right how does making a function call within this function cause the function to rerun right so what I can actually do here is in react I can have this they used state hook and then I can return this let's return it over the button right and when I click on this button I'm going to do something and in the button I'm gonna render out sorry my shift key but a MacBook Pro and the keyboards terrible so what I'm gonna

48:52 — do is I'm literally just gonna render a button with it with our count value right but what I can do is I can call set count so that'll be count plus one and what this is gonna do is I'm gonna call set count which is going to update my state value which in react internal logic is going to cause my component to rerun and this value here instead of it being zero is gonna be one right on the next function call when it changes because I'm going to count plus one so

49:22 — on the first render you can think of replacing this variable mentally think of replacing it with zero right and then when I call this obviously I'm gonna call set count one right and then you can think of this one and then that render is done that renders done we just need to render again so you can now again mentally think this is replaced with one this is replaces one this is replaced with one and then if I click it again it's gonna be two etc etc so this is how we can get this is how we can

49:53 — store a state within a react component right and that's basically what you use query does just in a more complex way so it stores our data for us in state and then when the when we fetch new data or when we fetch data the first time and when it comes back we set it sets its loading States to false and it sets the data state to whatever the data is cool does graph Cal have any disadvantages like optimization yes graph key oh so

50:25 — you can you can easily attack a graph kill in point if you don't think about guarding against it so there's a thing called query complexity in graph QL so if because graph QL allows you to fetch nested things let me quickly head into the playground and show you right so I can have have a user query so let's do that stretch out users right nafech my users and for each user I'm going to fetch two dues and for each to do I'm going to fetch the user and again I'm going to fix it two dudes and the ID for each and

50:56 — you can see that that fetches a massive amount of nested data and I can do that over and over and over again if I want to also imagine if I have a user's query here and for each of the users that we get back we return their to do we all sorry we return the list of all the doodles right what that means is I can write a graph calc rate that slows my data based on incredibly because what might happen if I haven't if I'm not using the rights like methods on the

51:27 — server to fetch my data from the database which when to touch on in a second how this might have white work is I fetch all my users I make a single query to fetch my users then graph chart goes and says okay I've got all my users let's loop through that and fetch all that reduce for each user right so that means n plus 1 queries write one query to fetch all the users and n queries which is the number of users to fetch to dues for each user so if I have 10 users I'm going to make I'm going to do 11 queries so there are ways to optimize

51:58 — this in graph QL you can use things like data loader I'd encourage you to just have a Google Checkout what's what's around but data loader helps with that basically what it does is it caches your graph calories and weights just a beat and then it combines your queries you're crazy to the database to make it more efficient I mean with query complexity and like kind of being able to attack the graph calc query there are very easy ways to to god that you can there are there ways to guard against a certain level of great complexity yeah

52:29 — will you create a new mutation to update the to do label no I would probably do it all in one so my a mutation over here can actually take in so if I got update to do I can say updates where ID is 1 and my data can include any wannabes I can update anyone I can even update the user if I wanted that's how I just set it up but usually for us how we do at named phases is you just pass in the object and if you include so you just pass in

53:00 — the whole object or rather you pass in the ID of the thing you want to change and whatever other fields you want to update and then as a result you just pull in which fields you updated and then the cache update loads automatically it does a puller of helpers for handling authorization on nested objects in the graph QL tree exact for example you want to limit access to the to dues for a user in a few seconds cycle code for demo yeah so

53:30 — there's some simple ways to do that Apollo has something called the public server and clients have something called context so your server when it receives a query can pull context from let's see if there's an example here so if you can pull context from your from your query and base it so for example what you can do is on the client side you can use in

54:00 — context let's quickly open up an example on the client side sorry actually other should work sorry okay there we go so here what we're doing on the client side is really adding an authorization header to our to any request that goes out to graph QL and our server can pick up on

54:31 — that because it's automatically sent within a resolver to context I can then just pull the authorization header off of it and then I can ball I can how I build my my logic is completely up to me another question I'm fairly new to front-end development how would you know when to use a REST API versus graph QL and if you were to use them together what would that scenario be it depends it depends I would I would suggest if you're new to front-end development

55:01 — try both I like graft yell more nowadays just because of the the speck that it gives me I've always struggled with risk because I never know what what like if I get a response back like if I create it to do what do I get back to I get it 200 saying that everything was fine or should I respond with a to one saying that the item was created so it's just graph QL is just way more straightforward and and doesn't have as many as much guessing as wrist because wrist isn't a spec it's just like a convention right yeah so I would I would

55:31 — just check out I would check out both but especially graph Gail is your code available on github not yet but please if you're interested follow me on Twitter and I'll post it real soon another question how would you use redux to store the data coming back from graph Keala for use and sibling or other components good question so you can use Redux and you can hook up you can so Apollo has its own cache so by default apollo uses its own in the memory cache but there are adapters for you to hook your apollo clients up to redux

56:02 — if you want to do it that way but what I can do is if I write this user query if I if I use this query in another component I can if I use this query in another component I what i can do is i can tell apollo to fetch the cache data first and then go make the query again to fetch the most updated a to all just use the cache data so instead of duplicating my logic and redux again i can just use the apollo catch to fetch

56:33 — my data using graph key i'll even if it fetches it from the from the cache right another thing i can do is if i have a component so let's allow to do item component right so in our to-do item component we even manually typed what we want to come in so we've typed that we want complete and we've typed that we want label to be passed in but if i want to say that for this item components i want specific fields from graph QL i can create what's called a fragment so i can define a new

57:04 — fragment i'm gonna call it item data and the fragment is going to exist on a to do object right and on this 2d object I want to pull complete and label and I can then type gymnast right so I can type gym this data this data fragment and I can replace my manual typing here with the types that are generated here and again what I can do is I can and if I don't want to have to like repeat myself here

57:34 — with the data that is needed by another component I can pull in that fragment over here so that's going to pull in the exact fields that I need for a child component which I could then pass it so what's cool about that is you can not only co-locate all your logic your markup your styling but you can also collocate your data requirements in one file do you have existing API is that graph Cal runs on or is there some mocking in the background so I think this question

58:09 — means what what do I have what I have running in the background here well I just have a very salt like a very simple service setup using Nexus and Prisma if you want to check out some really cool innovation that's happening in our em world check out Prisma it's basically what I have I can show you how everything is defined here and basically I just have a query I have a graph QL query this is not how we do things in production but here I just said that I

58:39 — have a query field that is a user type and it takes in a ton aware argument and returns a user and then I have my mutation so this is just a very very simple server setup but we we actually use a package called type graph QL to to render a to to to define our our graph GL schema and we actually define our graph Cal schema using type scripts on the server we have type script that translates to graph QL and then that

59:11 — graph QL gets translated to Thai trip to get on the client so it's typed full stack that's all from my side thank you everyone it's yeah it's it's a bit different doing a talk over zoom but yeah hope everyone enjoyed it and hope it was as useful as it would have been if it was in person and yeah stay safe and be well everyone and yeah check me out on Twitter if you want to see the open source this is the the code on github and the blog post that all come we'll

59:43 — see Thanks

Originally published on DevConf.