Using GraphQL, ReactJS and Apollo To Create Amazing Apps

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
I want to show you some cool stuff that I basically just figured out two or three weeks ago and we've already had we are already having this in production so and we are currently doing a huge migration basically killing of our entire REST API and switching it over to grass trail so I really want to share my enthusiasm and you know hopefully someone else can see the the you know the positive things about this and use it in your own projects as well so I want to show two technologies today one is graph queue the other one is Apollo graph scale is kind of one piece of the puzzle is on the backend Apollo is the other piece of the puzzle if you use some JavaScript front-end like angular or react Jas or react native or just vanilla JavaScript you can use Apollo as your client side piece of the puzzle so Apollo will talk to graph QL and graph your answer with data and Apollo will make sure that the data is distributed to all your components if you want to get an introduction to these two technologies best starting point is obviously the official website and actually the graphical website is so cool I don't really need to create any slides because they've already done it so we're essentially like okay what's gradual and you look at it it's like okay it's a query language for your API mm-hmm query language sounds like SQL and stuff like that so how does the query language look like right and you see it here it looks a little bit like a JavaScript object so you basically say okay I'm going to query a hero and I'm only interested in the field name and height and whatever and the response that you will get looks like this so it's essentially a JSON string that has the same structure as the query that you were requesting and you can you know you can have nested queries maybe the hero has a parent and that is also offer type human so you can you know with using the brackets you can go deeper and deeper and deeper and the response will look the same as well also going deeper in the same way okay so I mean writing queries like this is really easy you don't need to know anything about database design SQL joins foreign keys all that stuff anybody can understand these kind of queries right another thing is you have only one endpoint when you think about classic REST API is you have hundreds of endpoints probably and the developer every day when they start working and they're like okay I need to pick something on that shop grid okay what was the shop with end point again is it all product on product product / something so you have to go into your source code or look at your API documentation find the correct end point and then learn about what get parameters are possible and what response will I get back right and this is really painful slows me down as hell every day at work so with glass scale you only have one end point slash API for slash gql or slash graft whatever you want and your application basically these days if you use something like react J's or react native its current it's basically a composition of hundreds of small components right and react you build tons of components and each of these components they will have small queries of you know these kinds of queries here of the data that they want to consume like imagine you have a website on the top right corner there's avatar icon and other Chinese like the URL of the picture and maybe first name last name to render that at the top of the website so you would write a query like user first name last name avatar thumbnail or something like that right and you have tons of components and they all have these queries with normal REST API it's when I open my luxe gloss mobile app it sends 15 HTTP requests to my API I mean I should probably optimize that somehow but you know most people who just goofing around with mobile apps they will they will do it like this right with graph QL I only have one request because Apollo the client will batch all the requests in in a queue and every 10 milliseconds it will take all of them and merge them into one huge thing that looks like this right so I will have tons of small components they all have small queries like this this can be combined into one big string that contains everything and it will be like one request that is sent to your graph your back-end and one response coming back with all the data that you have requested also with classic REST API endpoints when I go to like slash products and I get a list of all my products usually I get like seventy fields I have like our database is pretty big these days and we have lots and lots of potential kind of information that we store for each product and my rest endpoint it returns just everything about that product even though when you have to shop great what what do I see picture price title that's it and then you click into the product and then you want to see all these other 50 things right and here you just define exactly what you want and and what's being sent back over the wire is exactly what you have requested and nothing more so you not only save requests which is like HTTP requests have to be build up its overhead all the time you also save bandwidth and you save space on the device because it's less or data that you have to save and memory right so this is pretty awesome basically the people on the back end and I won't talk about this today their task is to create the schema to describe how your data looks like and it doesn't matter what database you are using it could be Postgres could be MySQL could be MongoDB it could be there could be even some endpoints here with fields that you are taking from the Twitter API so you know your API could talk talk to another API and you can still query it in the same way like here right because under the hood on the backend what people will write in whatever language they use these are these things resolved by using normal programming functions and you can do in those functions whatever you want you can do it as you can do SQL query or you can do a request to some other endpoint okay so basic okay and because we have this schema here Brasel understands how your what data you have and there is a small web tool it's like an IDE that allows you to try out these queries and while you type it gives you code completion and because it understands that there's something like all films in your schema and it has name and climate and whatever okay here this is the planet it will when you say give me all films and then for each film give me title and opening crawl whatever this means here so it while you're typing this it already shows you what fields are available you don't ever have to look at any documentation you could throw a new developer at your project don't tell them anything just give them this and they type the first opening bracket and they see whatever is what endpoints are available right they choose an endpoint they type the next bracket they see what what what type is in there they type the bracket again they see what fields are available to sort of speak what columns are available in your database right you could just press the docs button here okay now it's here and you can see what-what are my end points in each end point what is the return value what data types are each field and those return values so and I and you don't have to write a single line of code to get this kind of documentation so believe me when you use this you're like efficiency will skyrocket immediately right okay I hope I could I sold you on this so the other piece of the puzzle is that's a back end right and we are not here today the four back end stuff we are here for front end stuff and JavaScript stuff so Facebook invented all this and Dave they release something called relay itright relay like two months ago when I already understood that this will be good for me but I totally fail and like after four hours I still couldn't get my react components to render anything from my database so I gave up I ranted on Twitter and then everybody on Twitter said hey bro why don't you just use Apollo it's like relay but easier so I tried that two weeks ago and it was easier indeed right after like 20 minutes I I could see something and then I went down the rabbit hole and now I'm sitting here so the poor documentation is quite ok you basically choose what front-end framework you are using and then you know just follow the initial steps how to install usually these these things here usage examples these are the ones in the documentation if you want to read about and then you might might need to dig deeper every now and then you will go here into the API reference and learn how it works internally more under the hood to do some more magic stuff like pagination and so on ok so much about the introduction so basically in this talk I will mostly copy and paste code from my slides into my editor because I'm too slow at typing to get this done in half an hour and basically if you want to try this at home you can just get these slides and you basically you know do the same that I'm doing right now here so I basically want to show you it's possible you can try it you know first of all if you clone this repository you will have to install a virtual environment with Python so you need to a little bit about pythons or just Google that install all the requirements and then you should be able to run a local Python server that should look something like this so manage my runs over and you should be able to go to this URL and you should be able to go to graphical and you know and then you're like hmm what endpoints are there right so okay there's some endpoint that gives me all messages and one endpoint that gives me one message so when I go to all messages that's pretty pie that all right what else do I need to do okay there's something like edges and something like node I don't really know what it means aha this is what I need ID creation date so these are the database columns that my message table provides right when I execute this I'm getting a JSON string with all my messages from my database all right so and this is how I would start working essentially I decide what I what kind of component I'm going to work on today and I figure out what query do I need so that this component can render later figure out the cream here and when I'm done and copy and paste that query into my actual code so we see we will see that later so basically that this Django server that I provide in the repository is just so that you have a graph graph your API back-end available for you to play around with and it only has these three endpoints like all messages one message and create a new message we will see that and at the end so so if you wanted to now you know start using react.js and apollo first thing you need to do is create and react jazz application and these days this is pretty easy you can do NPM install global create react app and then you execute create react app and you give it a name so you would do that when you clone my repository right there is already a front-end folder you can delete that folder and then start from scratch again doing this right I don't want to do this now because it's almost a lot of stuff from NPM so I just imagine I've already I've just done create react app front end okay and it creates the front end folder that's all it does okay so let's go into that folder and if it has worked you should be able sorry you should be able to do yarn start and this will open your browser and there is your react jas application that doesn't do anything right now okay so this is how you can start a new react project but we want to use Apollo and I want to show a list of items and then you click into one item you see the detailed view and I want to have another page in my app where you can create a new message so we need three pages and for that something like react router is commonly used so we also need to install react router so while you are here in your front and folder now we are in front and you would do your yarn at react router dumb and react Apollo I've already done that so I want to that again did I actually do it Anette correct router dumb ok maybe not I'm not sure okay so we are still in the setup phase of our project right we are still not really doing anything related to Apollo and graph show but we should have installed all the necessary prerequisites at this point in time and now we need to you know make sure that this default react application that we can see here shows something that we actually build ourselves so I will basically remove these imports here and I will remove whatever is in here and now the beauty of this create react app is did I stop the server yeah I did the beauty would have been that it automatically refreshes whenever you save your file alright so now it's empty and the first thing that we need to do when when we want to start using this awesome Apollo and crafts QL stack and react router we need to add a bunch of imports at the top of our file okay so we always have in every react.js application we have react import at the very top and then here we have to import three things that are related to Apollo here we have to import three things that are related to react router and here is our three views that we want to build today these files don't exist right now okay so we have these imports then we have to do some boilerplate code that you know I don't even know what it does this is what you find on the on the Apollo tutorial on the official website so essentially we have to use this create batching network interface function to create a network interface and we have to tell it and this is the important part where what is the URL of our graph CL endpoint so of your back-end server right this is the batching that I mentioned when you have a lot of components with lots of queries that will be put into a queue and you can define how many milliseconds Apollo should wait before it grabs all the queries merges them into one big one and sends them to the server so if you have some kind of add like a game or whatever that generates like requests on a per millisecond basis but you don't really need to send all these requests in real time you could you know set the best values to some milliseconds value here and this is this allows you to send additional HTTP headers to your server let's ignore that for today and then you just create an instance of Apollo client and then this is on the next slide we will replace our render function with this fancy code okay I have some syntax errors oh yeah this is because of my slides okay what's the problem here render return should we find okay there's one record missing all right so we have told Apollo where our API endpoint is and we have this Apollo client instantiated and now we essentially wrap our entire react application in between this Apollo provider component and we pass in the client that we have instantiated into that component who cares what this does below the right it works and it looks beautiful so just do it same for react router you basically have to wrap your entire app in between react router component unfortunately the react router component can only have one child component so I cannot do this this would mean we have one to child like routes and switch right we have to put one diff around everything and then here basically react router with version 4 with the new API works like this if the current URL is slash then at this space at this position in our HTML code like right behind this this render the home view component okay but if the URL is messages create then we will render that component so it kind of switches on and off which component is currently rendered okay and the switch thing let's ignore it for today it's basically because these two routes here they could be the same if you go to just slash create messages slash ID is also a match because this is a variable part in my URL right and maybe slash create is the variable part in my URL so and then you know I was like hey why why is it displaying both components at the same time and then I looked into the reactor rota documentation I figured out if you switch it goes down the list one by one and if it finds a match it stops and it only renders the component that it has found so this way you can make sure if you have ambiguous routes that could be like overlapping that it only renders the one that defines first okay so this is like a typical like all my react applications and also my react native applications the outermost entry point of your app looks always something like this all these kinds of wrapper components that add magic to your application okay okay so this will still not work because we have been importing three files that don't exist right now so I create a folder views and I create three files home view yes and detail view and create view alright and I mean these views are supposed to be a react component so we need to put a little bit of code inside so that they just do anything at all so I just changed the name of the class and put some title here so that I can distinguish them by like when we test them so we will have home view and finally hey where's my to tell you and while I was doing all this it kept refreshing the background that it's just now that was an error message right and now suddenly what's working again I love this so I could go to messages one and it's the detailed view rendering now I could go to messages create and is to create view rendering right and I can just go to the home page as a homely rendering so like our add skeleton is up and running so this is kind of the painful stuff that took us ten minutes that you need to do every time you start a new react project but you know it's not it's not that hard right okay so now we can do the exciting things so we want to learn about Apollo right and graft kale so first thing we want to do is how do I create some data I want to see some data out of my database on my website right so let's start with the home view first thing you do is you import gql and graph view from react Apollo and gql is basically I don't know it's just like a function that requires this kind of JavaScript string literal and this is exactly the query that in the morning when I started working I figured out in the graphical editor right you can copy and paste this exact query into here alright so and then we need to change our render function to actually use the data that we now have accessible in our component so let me paste in this new render function so alright so who has used react yes let's quick show of hands oh wow that's good that's like maybe 60% so most people will be familiar with this kind of syntax each react component right has this properties inside of this class I can always use this drops so these are things that have been passed into the component by some outside component okay so basically like if I would do something like this this info equals hello then and let's say this was my own live component then I could do this props info inside of my own disc component right so this is how you have to imagine how the properties work and because of graph QL we will have a field called data like we will have this props data available in our component because we enhanced our component was graphical is Apollo ok and the cool thing is data is another JavaScript object that has lots and lots of information in it and one part is loading so while your request is still in flight loading is going to be false and when the request came back loading is going to be true and when the request came back loading will turn to false right and every time a property changes the render function will be called again this is how react works so in the beginning when you first load your page there is no data so the query will be sent loading will be true and we will just return some you know loading stuff this is kind of like when you go through the Facebook homepage you can see in a timeline that there are these grey boxes like these fake posts while it's still loading and this is the kind of stuff that you would return here right you would return some kind of fake representation of the data that you will show soon but it's not there yet okay so once loading is done we we instead of rendering this we will render this right and so and we will have now access to this the props that data dot all messages which is the name of the end point that we have created here okay and then we know that we have to do edges dot node to get to the actual item and edges is a list of items so we can map over that list and for each item in that list we will render a paragraph and put a link inside so that we can click into that item so so in this case item is one edge right and we know that inside an edge that is note so I will have to do item node dot ID so this ID is basically the data that I have requested right and this message down here is also the data that I have requested in my query all right so hopefully huh oh yeah that that happened when I tried this earlier so I'm prepared for this I'm not prepared for this undefined oh yeah of course we need to go to the next slide first or actually we need to paste everything in this slide so the last part of the puzzle is this component currently doesn't know anything about this query right this is just a stupid react component doesn't know anything about Apollo or whatever so and this is why we imported graph QL we use gql to create our query graph scale is kind of a function wrapper or decorator all ever you want to call it and unfortunately you could use this graph QL query if you are like bleeding-edge super-modern yes whatever syntax but when you use create react app on the command line the bubble configure word or the es lin config is configured in such a way that you cannot use the decorator syntax yet so unfortunately this would be like super beautiful we have to do it in the manual way so we call the graphical function we put in our query variable right and we wrap our react component into that so now this graph fuel magic is wrapped around our component and this makes sure that this prompts the data and all this magic is available and hopefully bam we can see data okay so now the next thing you will ask yourself hmm how do I create queries where certain parts are variable like if we go to this URL this part of the URL is dynamic write this this dictates what kind of data I have to create from my database this is like the ID of the object okay and we can do that pretty simply so this is going to be our detailed view and once again first thing we do is we put the query in here and now it looks a bit different we have to write the keyword query and we have to say this is a query for my detailed view and actually you can come up with any name you could also call this product detail or anything right I haven't really come up with a good best practice yet how to name these things so I like to name them in the same name like the component is like this is the query for this component right so so far this has worked for me pretty well and I'm saying that this query has variables okay and it means there's one variable that's called ID and the type is this special kind of graph QL ID so you see these weird strings here those are graphical IDs you could have more things like you could say this thing also has I don't know limits and it's an int and it's a mandatory field so this is how you define your variables and then there comes the bracket and then it's the normal way how you would create things from your endpoints right so you would usually go and you can basically exactly the same thing that you just saw there we can also write it down here so we can say a query any name or web sorry query any name needs a variable ID of type I D is mandatory and when I execute this query I want to call my message endpoint and I want to clearly filter by ID using my ID variable okay and whatever I get back I want to have the ID the creation date and the message so I can't run that yet because there is no variable okay so when you have queries with variables you need to define them down here in the variable window and once again super smart it already detects what variables I defined up here and suggest them for me and then you just fill in the variable and you run your query and voila you get your data and then you copy and paste this whole thing into your react code and work just like that so the other way around is usually the case you try typing it here and it doesn't work and then you're like that why does it work and then you go to graphical you paste it in here and you get some nice error messages here okay so that's the first step we define our query second step again is to use the new data in our render function alright so same thing right while my query is still in flight I'm rendering some loading stuff once I got my data I have access to data so this drops the data and the message because that is the end point the graphical end point that I've created right and then dot ID creation date message because those are the fields that I have requested so I have exactly that data available in my HTML markup well in my render function okay and then I probably still oh yeah so the decorator part is a bit more tricky now all right so we have to read this from the bottom up just like before we are using the graph QL decorator right we are passing in our query and in this case we are passing in another JavaScript object with some extra data some options for my query and then we wrap our component in that wrapper function okay so far so good so how does this other extra options object look like so it's a JavaScript object and it has a key options and this can be an anonymous function so this syntax here might confuse a few people this book sorry this basically means our options isn't just a string or whatever this is actually an anonymous function and the first parameter of that function is the properties of my component okay and so this function returns another javascript object where the first key is variable and then I have one variable called ID and I'm now using props that match the parent ID so this is because of react router okay because we wrapped our application in between react radda radda radda does some cool magic and make sure that all my components have this props match available and if my URL had any variable parts so like if you use this coal on something right this is one of the parents so I have dot match parent dots ID all right so that means this is how I can access this outside information from the URL and getting it into my react component and now I'm passing it into my query variables for grass ql to consume okay so let's see oh wow it already updated itself so we can now go into each of our things here and it will display the value from the database okay and now this is something that I want to show you so I refreshed now let's let me go to the home page first so i refresh the page I get one request for graph here okay and I get back the result I go into the first object it's another request against my web server I go back to this page no more requests because Apollo because Apollo remembers what kind of data types do I have so in our case is the message object and what IDs do they have and it keeps the cache of all of them okay so if I go into the second one we have never seen that one yet so it's another it's another request if I go back to the home page no more requests if I go into the third one is another request and now no matter what I do I click around in my app no more requests but everything is in cache so that you get all this magic for free it's like really helpful for you know mobile applications where if the person is on a train for example the network suddenly gone those merits we can still you know move around user profile and and the latest tweets or whatever and can still see stuff alright so the final thing that I want to show today is how do you write data we have understand we can understand now how to query data even with variables so how do we write data in the graph QL world this is not called a query this is called a mutation and so that's why you have to write mutation and then as before I give it a name so this is the mutation for the create view right and if you want to create a new message there's one field a text field where you type in your message so this is kind of like the form data that we are about to send to our graphical endpoint and we say like the variables called message type string and this is the endpoint of our graph QL schema so we would do like mutation like new developer no clue was in system press control space I only have one mutation so it already completes to that one mutation that's available I press record it already tells me you need to provide a message right as a test and when you send a request to mutation end point it comes back with a result as well so what is the result it has two fields actually form errors and a message and we know that a message is also part of our schema so we might only want to have the ID because you know I want to save the message get back the new ID and then you could like refresh the page and go to the newly created detailed view of debt ID okay or actually in our case I would just go back to the home page so you know you can try that one oh it's even hey wait this should work oh no of course it works yet because I provided my variable here already okay so and I know this is pretty hard to digest now it's already a lot of codes and you're all tired but we are almost done only like two more slides with code and then we are done in my component I will I will define a submit handler so when the form is submitted I need to do some magic right and first of all I will prevent whatever the normal HTML form would do I will just stop that event then I just use the HTML form data API to fetch all the data from my input fields there's only one field that's called message right and now because of Apollo and because of the decorator that we will use at the end we have this props mutate available okay because this is a mutation and we provide the variables that are necessary you know we have defined that our mutation requires a variable so we pass in that variable by using that form data thing again and this is a promise so when you call mutate is a promise when the promise resolved so you say dot then in the end oh sorry whatever does okay when the promise resolved you get access to the return query here right so you get access to a rest data create message and then there might be something inform errors or maybe not if there are no form errors and there might be something in message if you are successfully created a message I think if I don't provide any text here there is something in form errors please provide a message okay I designed the graph QL back end that way so I will basically basically just check if there are formed if there are no form errors I will redirect to the home page if there are four errors you know you would usually use something like this dot set state errors and then you put the form errors in here so when you set the state your component re-renders right then you would you know put some kind of form errors component down here so when the componentry renders the form error appears okay so this is a it's really up to you how you actually display the form errors in your application okay so that was a that was the submit handler and then like in the other examples I will replace the render function with something more meaningful so I'm essentially just displaying a simple form like this just one form and one button right so this is a very normal HTML form it has two HTML input elements inside and it has this on submit handler here which is the function that we have created up here okay yeah so oh yeah and before this works we have to grab our component in the Apollo decorator and we have to remove the export default here so this is the same thing as before right we use the graphical decorator with this query in this case with this mutation that we have created and we wrap our components and inside so now hopefully there it is it works [Applause]
Info
Channel: Coding Tech
Views: 93,665
Rating: undefined out of 5
Keywords: javascript, reactjs, graphql, apollo, web development, software development, programming, coding, coding tech, learn javascript, javascript tutorial
Id: kXH2dbnHYA0
Channel Id: undefined
Length: 37min 9sec (2229 seconds)
Published: Mon Aug 14 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.