GraphQL for React Developers

Rate this content

There are many advantages to using GraphQL as a datasource for frontend development, compared to REST APIs. We developers in example need to write a lot of imperative code to retrieve data to display in our applications and handle state. With GraphQL you cannot only decrease the amount of code needed around data fetching and state-management you'll also get increased flexibility, better performance and most of all an improved developer experience. In this workshop you'll learn how GraphQL can improve your work as a frontend developer and how to handle GraphQL in your frontend React application.

112 min
07 Dec, 2022

AI Generated Video Summary

Today's workshop focuses on GraphQL for Front-End Developers, comparing it to REST APIs and exploring its operations and subscriptions. The workshop covers schema definition, data retrieval, and using GraphQL in the application. It also includes exercises on restructuring data, using named queries, and implementing Apollo Client. Other topics discussed are manual updates, mutations, and automatic data updates using refresh queries. The speaker also mentions the GraphQL code generator for generating TypeScript types.

1. Introduction to GraphQL and Workshop Setup

Short description:

Today's workshop will be GraphQL for Front-End Developers. You will learn what GraphQL is and how to use it in your project. We'll be building a front-end project using GraphQL as its API. I am Roy, a software developer with experience in coding, workshops, and training. I work for StepZen, a GraphQL as a service company. In this workshop, we'll focus on the frontend part, including interaction with the GraphQL API, using GraphQL clients, and possibly TypeScript. I've set up a repo with all the materials for today, including exercises and solutions. You can find the link in the chat. Before we dive into the details, I'll give you a basic introduction to GraphQL and compare it to REST APIs. Let's start by looking at a REST API and its limitations, particularly when building a future-proof stack like an e-commerce platform.

♪ Thanks, everyone, for joining this workshop. So today's workshop will be GraphQL for Front-End Developers. So what we'll be doing today is you will learn what GraphQL is and how to use it in your project. And also, most of the time you will be spending inside a project. So we'll be building a front-end project that is using GraphQL as its API.

My name is Roy. I am, well, most of all, my software developer. I've been developing code for a long, long time. Even before I actually started working already I was developing code at home when I was in high school. Currently I work for StepZen, which is a GraphQL as a service company. So with StepZen you can easily set up GraphQL APIs. I also give workshops and trainings to my own company HackTeam. And you might know me as the author of several programming books. And besides this, I also run a small YouTube channel on which I do live coding sessions and also post videos about technologies I'm using.

You can also find me on Twitter, which handles the account HackTeam. If you are on Twitter, I'd be happy to connect there. So you can get any information about the things I'm working on and maybe ask questions there as well later on after the workshop and you're trying to fiddling with GraphQL. And maybe you'd like to learn more about all the GraphQL technologies out there. So that's about me. Back to today's topics. What are we going to be handling today? It's GraphQL. You can only use GraphQL if you also have a GraphQL backend. So part of what you ever do with GraphQL also depends on the backend that you're using. But today, I already created an API for you that you can use, so you don't have to worry about creating the backend at all. Although, if we have time and if you have questions about how to build a GraphQL backend, of course, I can tailor the workshop better to your needs and answer any questions that you might have. But today's focus will be mostly on the frontend part. So the right side of this diagram, so the backend's already there, you don't have to worry about it. What we will be building is the frontend part, so the interaction with the GraphQL API, how to get data out of there, how to use GraphQL clients. Maybe if we have time, also some TypeScript as well, that might be cool. And for this, I've set up a repo that contains all the materials of today. So if you would go to the repo, you can scan the QR code if you're on a computer anyways. Let me try and copy the link in the chat for you. It's probably easiest. And in this repo, you can find all the materials we have for today. So once we start working on the exercises later on, we will be walking through the repo and see how it's set up and do all the exercises from there as well. And most of all, you need to go inside the introduction directory. So I just sent you the link in the chat. So everyone should have it now. In this repo, you can find all the materials. You can also find solution branches that contain the solutions to the exercises we'll be doing today. And this is for yours to keep. You can bookmark it somewhere and always go back to the materials later on, in case you might want to retry some of those, or in case you need to leave early because of work or family obligations. The links here on the screen. It's also in the chat, so go to the chat, please. And there you can copy it and open it in your browser. You don't have to do anything in the repo just yet. We'll be going over that together later on. But first, before going into the details, before I start encoding, let me give you some basic introduction about GraphQL, what it is, how to use it and most of all, how to compare it to REST APIs. Because people actually like to say that GraphQL is a replacement for REST. I don't really think it is a replacement for REST. It can actually play together well with REST APIs. Typically, I like to say it's a better version of REST. But you can still use REST that would better fit your project or maybe your team that you're working with because most of all technology is being built by people. Well, if you prefer REST APIs, that's probably fine. But in this workshop, I'll be showing you why GraphQL might be a better alternative to you and how you could use it inside your projects.

So to do this, let's have a look at a REST API first. So one common trade of REST APIs is that they have multiple endpoints. Typically, when you interact with a REST API, you don't interact with a single endpoint. You maybe have one, two, three, five, or maybe tens of different endpoints. If you're building something production-grade with REST APIs, you might even have like 100 endpoints or more. So suppose you were working on this great project, and I always like to start off with an example. Suppose you start working on the e-commerce platform of the future. So maybe you get proposed, you get this proposal by a recruiter or maybe your manager comes to you and tells you were going to be building the e-commerce platform of the future, of the feature. And this future e-commerce platform has to come as this stack. So it will be having a database, you have a REST API, you have a reactive application, and it's also using JavaScript. And maybe there's already some logs being created for this project as you see on the left, it will have maybe a mobile page in which you can find this specific product, so you can find its title, its thumbnail, its price, the categories, and also the rating. And if you ask me, it might not even be the e-commerce platform of the future, because there are some red flags to me, if you're building something that should be future-proof. So why is that? So I would say it isn't really a future-proof stack that people are using for multiple reasons.

2. GraphQL vs REST APIs

Short description:

REST APIs have multiple endpoints and fixed data structures, which can lead to inefficiencies and excessive data retrieval. GraphQL solves this by using a single endpoint and flexible data structures. With GraphQL, developers have control over the data returned. A GraphQL request is similar to a curl request to a REST API, but it is layered over HTTP. GraphQL is transport layer agnostic, but it is commonly implemented over HTTP.

Well, of course, the REST API as today is a GraphQL workshop, of course, it would be weird not to have something against REST APIs. So I would be saying if you're building something that is future-proof, REST API might not be the best choice for several reasons. But most of all, because maybe at some point you try to introduce more clients, so maybe next to a mobile app. You also have a web app, you maybe have an admin panel that's using the same set of APIs, a REST just isn't tailored for these needs. And I will go into more detail later on.

And then the second potential red flag I see is JavaScript. Although JavaScript is a great language, if you are starting to build something, something big, I would say always try and use TypeScript. Well, for many different reasons. And that's why also we'll be introducing some TypeScript later on at the end of this workshop. So being the brave developer you are, you just start building with this REST API. Now, let me explain you why the REST API might not be the best solution for this project.

So with this REST API, you probably need different endpoints in order to fill the UI that you're seeing on the screen. So you would have general product information that may become a slash products, slash endpoint page or endpoint, actually. So this endpoint will provide you basic details of the product, like title, like a price, maybe also the thumbnails. Or maybe the price is even coming from a different endpoint. I mean, it's perfectly viable. Then you may be also want to show like some breadcrumbs of the category this product is placed in. So you would have to add another endpoint that gets you the information about the category this product is placed in. And then maybe also have a third endpoint that gives you information about the ratings for this product. So that's already three endpoints that you might be needing. And you maybe even need more endpoints, right? Like I said the price, maybe the price comes from a different endpoint as well. Or maybe your price also is impacted by the location of the person viewing this page. And it's probably also need another API endpoint in order to calculate this. So typically with REST APIs, you have to call different REST API endpoints in order to fill one simple UI. And besides having to use multiple endpoints, which is the first trade of REST APIs.

REST APIs also will return fixed data structures. So there's a second trade of REST APIs. You don't only have a single, multiple endpoints. You also have fixed data structures. So what does this mean? If you have a REST API, it's typically directly linked to a database. So if you have a product's endpoint, there probably is a product's table in your database that you're using to get this data. Similar for the categories for a product, you probably have some table in your database that links a product to a category. So this relational table probably has its own endpoint and then returns you all the different tables this product is placed in. And then the ratings for this product will probably also be in a different table there. So you would have a table that consists of all the different reviews of this product. So REST APIs have these fixed data structures and these multiple endpoints because they're directly linked to an entity in your database. At least that's how it typically works and that's how REST API started anyways. So if you would look at this example, it is still the three different REST API endpoints and in here you can see the fixed data structures. So you can see these REST API endpoints will typically return all the fields that are available in the database table for products, for product categories and also product ratings. Well, maybe in your UI you're only using a set of fields, you're not using all the fields, you're only using a small percentage of all the fields that are in a database table. And of course there are things you can do to optimise this but in the end, your database should consist of all the data related to all these specific things. So maybe you don't want to solve this in the API layer. So having these multiple endpoints and these multiple, or actually these fixed data structures. They'll need for your front-end UI that you have to make different requests to REST API endpoints. And then you also get tons of results for these different endpoints. And you need to filter out the fields that you want to use because maybe also you're only showing the title and the price while the product standpoint returns way more data. Same can be said for like the categories, maybe they have descriptions of the categories. Maybe they have ratings for categories, images for categories. They have way more information about categories probably. And the same can be said for ratings. Whenever you load your first screen you maybe only want to show the average rating and number of ratings. Well, maybe if you go to the reviews page for this product, you want to show all the reviews one by one. So this is a lot of data and a lot of requests that you need to do. And this is still simplified because probably there are way more endpoints that are in there. So endpoints for stock, maybe a specific endpoint for pricing. Endpoints that show maybe sales or discounts, endpoints that will get maybe different offers. So maybe you're building a marketplace and you have multiple companies offering the same product. So there's tons of things you maybe want to show on this page. So GraphQL solves this problem that we have with the multiple endpoints and also the fixed data structures, which is a common trait of REST APIs that you can work around, of course. But if you are working around it, you will get something they call a REST-ish API. So it's a REST API, but it's more like a REST-ish API, because it's not REST full. So if you have a REST full API, you would have these different endpoints and you would have these fixed data structures. Sometimes developers work around this and use parameters to limit the scope of an endpoint. I would say it's something you shouldn't be doing because, well, you never know what will happen. So GraphQL solves this by not having multiple endpoints, but instead having a single endpoint. And then instead of having fixed data structures, GraphQL has flexible data structures, meaning that you as a developer have control around the data that's being returned. So how did this work? Before I'll go into details, let me show you a GraphQL request. So a request to a GraphQL API is very similar to doing a curl request to a REST API. It's still layered over HTTP. So GraphQL is transport layer agnostic, but typically people are implementing GraphQL over HTTP, meaning that you can still do a curl request, it will always be a post.

3. GraphQL Operations and Subscriptions

Short description:

GraphQL uses a single endpoint and supports multiple operations: query, mutation, and subscription. Queries retrieve data in a read-only way, mutations are used to modify data, and subscriptions enable real-time data. Today, we'll focus on queries and mutations. Subscriptions will not be covered due to time constraints.

And I will explain to you why it's always a post request. Because with GraphQL, as we have the single endpoint, you need to let GraphQL know what data should be returned for this endpoint. And therefore you need to append a body that contains a GraphQL document. And in this document, you describe the operation type. And there are multiple operations. The most used one is a query, which is very similar to a get request for rest APIs. So with queries, you can retrieve data in a read-only way. And then you also have mutations. These are used to mutate data. So let's say you want to mutate data, let's say you want to change the information you have for a product. You would use a mutation. And with one mutation, you can add new data. So it's quite similar to a post. You can make changes to existing data, so this will be a boot or patch, but you can also delete data. So this will be similar to a delete method. So GraphQL actually simplifies all these different ways of mutating data that you might be used to for other HTTP formats. And there's also a third GraphQL operation, which is called subscriptions. And these are used for live data or real-time data. So if you're building a jet application or maybe like a stock tracker, you want to be using subscriptions. And we will be using subscriptions today as they are a bit more advanced and we just don't have the time for it. And in most use cases, you probably aren't working with real-time data anyways. But it's good to know that they exist. And I'll be happy to answer any questions that you might have around subscriptions at the end of this workshop.

4. GraphQL Schema and Data Retrieval

Short description:

GraphQL starts with a schema that defines types and operations. The schema describes the data structure and relationships between types. To get information from a GraphQL API, you send a GraphQL document with an operation, like a query. The response is always JSON and has the same shape as the operation sent.

So what does GraphQL look like or actually how do we get to the single endpoint and the flexible data structures? It all starts with a GraphQL schema. So whenever you're designing a GraphQL API or interacting with a GraphQL API, is a GraphQL API will have a schema. And you as a developer that is consuming this API will also have access to the schema. Maybe not the complete schema, but at least the subset of the schema in case anything is hidden by authentication.

So on the left, you can see a GraphQL schema. In the schema, there are types defined and there is also operations defined. So this operation will have three different types, this product, review and offer, and as well as one query, so one operation, which you can use to retrieve a single product based on its ID. In the schema, the data structure is described. So you can find all the information about the GraphQL API, about the schema, about all the possible operations, and also, all the return types or input types for these operations. You can find the possible queries in here and all the different types are set, like type products, type review, and you also have relationships between types.

And then to get the information of a GraphQL API based on the schema, you need to send a GraphQL document, and this document contains a operation, like the query you're seeing here. So with this query, you are retrieving information about a product, you are giving it a parameter, which is number three. So, this is number three, product ID, and then you are defining all the fields that you like to see returns. So these are title, thumbnail, also some relational fields, like the count of the number of reviews and also the average rating for all the reviews. Besides this, you can see we also are getting information about offers, like a reseller and a price. So, this would be a schema that would be fitting to maybe a marketplace, like Amazon. So in here, you specify the data, which you like to be returned, and this operation will be sent together with the request to the GraphQL API. And you also set dynamic parameters and all the data you like to be returned. And then the response of the GraphQL API will always be JSON. So it's important to remember, the response is always JSON. And then you can also see the response has the same shape as the operation we sent to it. So you can see, we have a query called product. We have a title, thumbnail, we have related data. So it's a predictable return result, and it has the same shape and structure as the query that you sent to the GraphQL API. So I hope this sounds very clear.

5. Introduction to Workshop Setup

Short description:

If you have any questions about GraphQL, we can have some time now to ask these questions. We will be answering the questions as soon as possible. The implementation will be on the front-end side. Clone the repo and run npm install or yarn. Move into the introduction directory. Inside the introduction directory, you can find a readme with setup instructions. After the installation is completed, run the development server. We will be using GraphQL instead of REST API. We will be implementing features like viewing the detailed page, using filters, adding pagination, and adding upvotes. We might also convert this app to TypeScript.

If you have any questions about GraphQL, about GraphQL as a concept, we can have some time now to ask these questions. So feel free to unmute yourself or raise your hand or type a question in the chat. If you have any GraphQL concept questions just yet. Just to make sure that everything is clear, we will be answering the questions as soon as possible. We're a little bit later already before we dive into any examples later. So the implementation of today will be, on our desk, because this is already being done for you. The implementation will be on the front-end side. For this, I would like you to go back to the GitHub repo. The link is still in the chat. Let me see if I can actually pin this in some way. I don't think I can. That's okay. So please go to this page. Here you can find all the exercise we'll be doing today and also some general set up instructions. We'll be going over this repo together as a group. If you would go to the GitHub repo, make sure to go to the Introduction page, to the directory called Introduction, because that's where we'll be starting today.

In here, you can find a simple project set up. We have a package JSON to set up the Next.js, I think it's Next.js, I guess it's just Create drag, to set up the Front End app. We also have a steps and directory and this is where the GraphQL API lives. And as I told you earlier, you don't have to make any changes to the GraphQL API at all. So, this GraphQL API is just there to help you building the Front End app and understanding all the concepts. So, to get started, you have to get started by cloning this repo. And you can also fork it of course, that way you are certain that you will have a copy of your own. So, if I would be making any changes to this repo later on, you might lose the information in here. So, make sure to fork it as well, that way you are certain that you will have this information for, as long as you keep your GitHub profile open. So, clone this repo and then you can run npm install, or yarn, depending on what you prefer, and move into Directory Introduction. So, to clone this repo, you can just use, let me see where is it, you go back to the previous page where it will have this code thingy. If you would copy this, you can copy this one here. I guess you can also, well, take the URL from there, so you can copy this one, and then if you would be going to a terminal, I usually use VS Code, and you could just type git clone. Clone, and then append this address, and it will clone the repo for you. I put this command in the chat for people that maybe aren't that familiar with using git clone. So if you are using git clone like this, you will get a local copy of the repo on your machine, and then you would have to cd into the introduction directory. After cloning, let's assume you've done this, and I'm not going to be doing this as I already have it cloned on my device. I would have this, so I would have two directories on my local machine. I would have the introduction and the advance directory, and I would have to move into the introduction directory by using cd introduction. This will make the working directory of my terminal, the introduction directory, instead of the project route, which contains both the introduction and the advanced section of today's workshop. And you probably will be able to finish the introduction part, which we won't be able to finish the advance section as well. But as you have the repo, make sure to clone it and fork it. And then you will be able to fix this on your own time, or maybe at the end of the workshop, if you still have time. So make sure you are inside the introduction directory. And in here you can use npm install, like this, or you can use YARN in case you prefer to use YARN. I guess I'll say I'm old fashioned, so I will be using npm install to install all the dependencies I need in order to run the front end projects for this workshop. While we're waiting for this to finish, let me know in the chat if things are going too fast. You might need some extra time. It's fine. We can always slow down a bit to make sure everyone is able to settle their project. So let's continue from this part on. Inside the introduction directory, you can also find a readme. What I would advise you to do is have your VS code or your auto editor open at all times to run the project and then keep the browser tab open to find the introduction readme. You go in here. I can find the readme in the introduction directory, which includes the setup instructions, which I just walked you through. We can do npm install and then we can do a yarn. After the installation is completed, we can run the development server. Go back to VS code, I can do npm start here, and this will start my react project, and this will show the application we will be working with today. So you would see this application. It is indeed a bit of Hacker News, so that's what we will continue building on today. For now it's using a REST API. It is using the practical dev REST API so it's not actual data from, it's not data from Hacker News, it's data from practical dev, so, and as you can see, these are all the articles that have been posted, maybe today and tomorrow. And what we'll be doing in this workshop is we will be using GraphQL, instead of REST API, which we're doing here, we are implementing all cool stuff, like viewing the detailed page, like using filters, we'll be adding pagination. We also will be adding upvotes, you can upvote articles or posts in here and you can also view the number of upvotes, and then we might also be able to convert this app to TypeScript. So that's in short what we'll be doing today. To go back to ReadMe, you can see we have this set up, and then we can go to exercise number one. And we also need to install the steps and CLI first, because now we have the application here, which I just showed you. So this is using REST. What we will be using is GraphQL instead. If you look at here, we have a directory called steps, and this has a mock GraphQL API. That is using the practical dev API, and it's also using a Firebase database in which we store the data, and it also has a mock authentication server. So this is a mock GraphQL API that you... Well, it's not a mock API, but it's being set up for you. You don't have to make any changes to it.

6. Setting up the GraphQL API

Short description:

To set up the GraphQL API, run the application and open a second terminal. Make sure you are in the introduction directory and run npm install globally steps 10. Optionally, sign up for a free account to get a secure API. Run steps and start to deploy the GraphQL schema on a GraphQL API. Check if everyone can see the GraphQL API in a browser. We're now ready to start building and using GraphQL on the frontend app. For the first exercise, run a query to retrieve the ID, title, and description fields of the articles. Use GraphiQL to explore the available queries and mutations. The GraphQL API returns the same data as the Practical Dev REST API.

The only thing you need to do is run it. So as soon as you have this application running, you need to open a second terminal. You can either split it or open a new terminal window. Let me just quickly do this. So I will create a new terminal window. And in this new terminal window, I need to make sure that I am in the introduction directory. And then there I just run npm install, globally, steps 10. So this will install steps 10, which is a GraphQL service that allows you to create GraphQL APIs declaratively. And I already set up a GraphQL schema with steps and in here. So you don't need to make any changes to that. The only thing we need is installing the CLI. So we're able to run the GraphQL API that we have in there, because we'll be using this GraphQL API to use GraphQL in the front end app that is also inside this repo to make sure to install it. The command to do so is also in the README of course. So to get a free GraphQL API, you can install this by running npm install globally, you get to install the CLI, which I've done now. And then after installing the CLI, you can optionally sign up for a free account. So if you would sign up for an account, you will get a secure API that also remains up for a longer time. You can also choose to not sign up, which perfectly fine, of course, and then you can run with a public account. And it has one caveat, if you use a public account, your data will be deleted in like 14 or 30 days. So if you wanna keep this application up, you probably have to sign up for an account. It's also a bit safer because that way you're sure no one is able to retrieve your public GraphQL API. But in case you don't want to do that, it's also perfectly fine. So let me see if I'm logged in. Yes, I am. Yes, I am logged in. If you're not logged in, it's also fine you will get a question to ask if you wanna continue with a public account or you wanna sign up for a free account to run the GraphQL API. The only thing you need to do is run steps and start. So this will take to GraphQL schema that is inside the steps and directory and deploy it on a GraphQL API for you. So if you are signed up, you will get a local host thingy like a GraphQL to help you use it. Or if you have signed up, you also have this production ready endpoints. If you use an anonymous account, your endpoint will start with HTTPS and then public with some random string. And you can open that one in the browser as well. So if I will be opening this in a browser, I can see a GraphQL that looks something like this. So this is the old version of GraphQL. Here also is a new version. See if I have it somewhere. A news app. So this is what you would be seeing if you are using a public account. You will be seeing the newest GraphQL, and for signed up accounts we're in the process of making the latest GraphQL available for signed up accounts as well. So just to check in, is everyone able to see the GraphQL API in a browser? So either on a local host end point or on a public end point. And this is what we, this is everything we need to set up for the GraphQL API. From this point onwards, we will be consuming this API only. So there's no more set up after making sure you have this thing running in the browser. So let's do a quick round of the check marks again, to see if everyone is able to have a GraphQL API running. So we have seven check marks now, let's go to 10 again. So we're sure we have most people with us still, and it's important to have the GraphQL API running because you will be needing this to complete all the exercises. As of course we need a GraphQL API in order to do the GraphQL workshop. So now you just need one more person to verify that they have the GraphQL API set up, and I'm gonna be assuming the number of people to be, well, following on, maybe decrease a bit as people might have to tune out for work or family stuff. So I guess that's 10 out, great. Okay, so we can continue. If you go back to ReadMe, you have cloned the repo, you have installed all the dependencies, you have installed the StepSteps CLI, which we need to run the GraphQL API, and now you've also run the GraphQL API itself, meaning that on the setup side, we have everything done. So we're now completely ready to start building, to start creating, start using GraphQL on the frontend app. So for exercise number one, you need to have the GraphQL API setup, which we've just done, and here the first exercise is run your first query. So what's the query look like? And we want to retrieve the fields, ID, title, and description. So to run your query, you can either run your query against the GraphQL API using curl or using postman. But for this, we'll be using GraphiQL. So GraphiQL is the explorer that you're seeing here. Whenever you open the endpoint that you see in your terminal. Whenever you do run steps and start. So it's either the localhost one, or it is the production ready endpoints, which either starts with your username or starts with public and then some random string. But for exploration, I would say open the localhost because it's made for exploration and you will get a GraphiQL. So it's either the old version of GraphiQL or the newer version of GraphiQL, which is this one. In both versions of GraphiQL, you can find the schema by clicking on Docs. When you click on Docs, you can find all the available operations, the queries and mutations. And also in here, it's on the left side, you can open Docs and you can find the queries and mutations. So once you press query, you can see a list of all the available queries. And the same, if you click Mutation, you can find a list of all the available mutations. So these are the queries and these are the mutations. Before this first exercise, I want you to retrieve the articles and then take the field's ID title and what else do we have here? ID title and description of the articles. And this GraphQL API is returning the same data as you're seeing here, because what I've done using StepZen, I graphicalized the Practical Dev REST API. And this is quite cool because that way I can use GraphQL for a REST API and for a product that doesn't have a REST API.

7. Retrieving Articles and Adding Usernames

Short description:

To get articles using GraphQL, open the docs and find the available queries. Use the articles query to retrieve the ID, title, and description of all the articles. You can also provide arguments for pagination. To add the username of the article's author, inspect the GraphQL API schema and find the user field. Use sub-selection to get the username field for the user. GraphQL provides auto-completion for easier query building. This is how you can use relational fields in GraphQL.

And I can also combine it with data coming from different sources, such as Firebase, as we'll be seeing later on when we implement the influence. So to get the articles using GraphQL, you can find out which queries are available by opening the docs by clicking on Query and then find the list of queries. And then the same in the new version of Graphical. You can follow the same steps, go to Query, and then, I don't know, take any of these queries.

So for exercise number one, you can either try it yourself or we can just do it together as it's just the starter exercise. I propose just to do it together as a group. So what we'll be doing here, whenever I want to do a operation, I just start typing the operation type of force. I'll be typing query to let GraphiQL know that I want to send a operation that is a query. And then I open this query using curly brackets. And then here, I need to define the operation name. So it's not a query, it's not the operation type, which is query, but the name of the operation. And in my doc step here, I can see query and then I can find all the possible operations that are queries. So if I want to get a list of articles, I probably need to use the articles query, as I see here, which I can just type like this. And you can see there's also this nice auto completion coming from GraphiQL, which is really helpful. So I use the articles like this. I can also provide arguments. So these are page, per page and text, but it's something I will be doing just now.

So instead of providing arguments, I will be using a second curly bracket to list the fields I want to use, and to find all the available fields. You would click on the article because articles the response type. And if I want the ID, I see, I can just type ID. I already see that ID is of type integer. It doesn't really matter right now, but it's useful to know later on, you can type ID. Again, you have to auto completion, which is quite nice. If we scroll down, you can also find the title probably. So the titles also type, it's a type string title here. And the final field I want is description. And I can see description is also in here. It's also a string. Just start typing description. So this is my query. I can use it to retrieve the ID title description of all the articles of Practical Dev using this REST API that I have running now through the repo we set up at the beginning. Once I press Play here, I will get a list of all the articles. And as you can see, these aren't the same articles that I'm seeing here probably. If I refresh, there might be some new ones. So you can see super-useful CSS resources, Meme Tuesday, and you can see the same results there. I can also copy this and use it in the latest version of GraphiQL, which should give me the same results. And this is basically everything you need to do for exercise number one.

So quick check-in, is everyone okay right now? Did everyone understand what's going on? If not, please let me know. Use the chat, raise your hand or unmute yourself to ask any question. Okay, I see some thumbs up. See some green check mark, so we're gonna be assuming exercise number one was clear to everyone. So for exercise number two, and I want to take, let's say five minutes for this, I want you to add another field or maybe more fields to this query. So if you go back to GraphiQL, I want you to get the username of the person that wrote the article as well. So for this you need to make some changes to the query and let's take five minutes for this, so for exercise number two. So let's take five minutes and then we'll do it all together so you can see the solution for it. And it might be that these first exercise are a bit slow to you if you already aren't familiar with GraphQL. But to make sure that everyone understands what's going on from different experience levels and different experiences with GraphQL, it might be starting off a bit slow. If you do generally feel everything is getting a bit slow, feel free to work ahead as all the exercises are in the repo and they are available to you. So for exercise number two, can you alter the query to also get the username of the user that wrote every article? And for this, I gave a small hint, so think back to how you inspect a GraphQL API schema. And for this, let's go back to the graphical in where you can see, you should click on Docs. You can find all the different queries. And then we would go to our articles query and we go to the response type, which is article. It might make sense to look in here for user Is there a way to get the user? You can see there is a field called user, but if you click on it, you'll see it has a response result type of its own, it is not a string. So it's a, what we call a custom scholar or relationship. So it is a field on its own and it also has different information. So what we need to do is start typing user. And then again, we need to open the, we need to use security brackets to get sub-selection of fields for user. And then here we can start typing username and it should get us the username for this user. And then we can see whoever wrote these articles in practical depth. Which you also could have done maybe if you're a bit smarter or a bit more hacky than I am, just start typing, start typing user, try it out. And then you can see GraphQL, GraphQL did it for us. So yeah, I see Diego was smarter than me and actually followed this pattern. So that's also a nice way to do. And it's also a cool part about the graphical because if we have this, we have this out in completion. So it will help you do these kinds of smart things. This is how you would use relational fields. And in the case of practical depth, this is all coming from one rest API. Maybe if you're working with a GraphQL API based on top of a database, these relational fields might be coming from different database tables. So that is something GraphQL can offer you as well. So if you have a articles table in your database, maybe also have a user table.

8. Using the GraphQL API in the Application

Short description:

In this exercise, we'll be using the GraphQL API instead of the Practical Dev REST API. To do this, you need to go to your application's source directory and open the homepage component. In the fetch function, replace the REST API endpoint with the GraphQL API endpoint. Remember to set the method to POST and the headers to JSON. If you have a StepZen account, add your authentication key. Finally, pass the GraphQL query to the endpoint and ensure everything renders correctly. Take 15 minutes to complete this exercise.

So this data could be coming from different data entities. But for you as an end user, as a developer interacting with the GraphQL API, it doesn't really matter where the data is coming from because well, you can easily use it like this. Circling back to the README in GitHub.

We're going to the first a bit more complex use case. So for exercise number three, you can read that GraphQL-APIs can be queried from a client application. So in this exercise, we'll be using the GraphQL API that's been just used. So we used it inside the database data database, like the exploration tool, GraphQL. Now we will use it inside our application.

So we have the GraphQL here. So we're going to be using this query inside our application instead. So what you would need to do, you would need to go back to your application is running. So for me, it's VS Code, it might be a different editor, in case you're using maybe WebStorm or some IntelliJ things or maybe Adam, could be anything. And maybe you're one of those Fim developers, which I always envy a bit, because well, I wouldn't be able to do it myself, but I always envy those people that are able to do anything in Vim or VMAX or whatever the cool terminal tools are called nowadays. But for me, the editor of my choice is VS Code.

And in here, I would need to go to the source directory. And in here, I can find several components, and I need to open the homepage components. In the homepage components, you can find a fetch function that is getting the information from the Practical Dev REST API. So the information you are seeing here, sorry, here, this information is all coming from this fetch request. But as you see here, it's coming from your REST API. What we want to do instead is we want this information to come from a GraphQL API.

So what I need to be doing is I need to take my GraphQL API endpoints here. And then we need to swap this out. Bit like this. Or if you're using a public endpoint it should be something like this, public and add some random string. It usually starts with like a number. So any of these two endpoints, either one that has your account name or the one that starts with public. And what's important to know here, never use the local host endpoints. Local host endpoints. As it won't work. So you want to use the GraphQL endpoint instead. You probably also need to append some headers. And maybe also remember that you need to set the method to post. And then you need to set some headers, which I will actually give you away just to make sure that we don't get confused about this. You always need to set the content type to JSON because GraphQL APIs only work with JSON. And then if you have signed up for a StepZen account, you also will need to add your authentication key here. So we need to type authorization. And you would need to type API key. Your StepZen API key. And then if you have the issue, we need to go to here to get your API key. But it's optional. You don't have to do this, of course, if you didn't sign up. So this is the first part. And then comes the most tricky part is how to get the GraphQL query to this end point. And for this, I will leave it up to you to finish. Here are some pointers. What I want you to do now is to take 15 minutes to hook up your GraphQL API in this fetch request. Pass the API key to it optionally, pass the query to it. And also make sure that everything renders nicely. So maybe you need to destructure some data here. So what I want you to do is replace the REST API with the GraphQL API. So this is exercise number three. There are some hints in here. Make sure to add the authorization header in case you signed up. And also have a look at the network tab in GraphiQL to get any pointers to how the HTTP request is actually being sent. Get back a bit earlier, I see some interesting questions. Why everything is a POST meadow? It's because we need to send a query. So if you have a get, you cannot attach a body. So this is only if you set a POST. So that's the reason why we need to use a POST request because we have a body that contains our query. And this query is something we can get from our GraphiQL. Just take this query, go in here. And then you actually need to name its query. And this will be a string that contains this, but probably, as I have a multi-line, I want to use this, make it a bit nicer looking. If I would format this, I would need my API key in case I have authentication here, which I actually have. So I have the GraphQL API endpoint. I'll make sure to never use the localhost as it won't work. I've set my methods to post. I've set my headers, which are the authentication key in case you need one. And I also set the content type, in this case in JSON. And then in the BUDDY, I appended the query I want to use.

9. Restructuring Data and Fetching a Single Article

Short description:

To fix the data format issue from the GraphQL API, restructure the data by checking if the result has data and articles. Use the data.articles field to restructure the data. For Exercise 4, you need to get a single article from Practical Dev using GraphQL. Make changes in the code to fetch a single article. Use the ID of the article in the query. Take 15 minutes to complete this exercise. If you encounter a 401 error, ensure you use the correct endpoints and headers with the API key. Do not use the localhost endpoint for code. Copy the fetch function to the article site and modify the query to get a single article by providing the ID as a string.

So we'd save this and I would go back to my app. I would probably start, I would refresh this because the data format from the GraphQL API is a little bit different. Let's go back here, the request succeeds. I have a GraphQL request, returns my data. I can see the data is here. But as you can also see, is the request from the API, from the REST API was different. And our data is nested inside data.articles. Tiny bit bigger for people with bad eyes, including me. So what I would be doing here is my results. I should check actually if result has data and has articles and then I should put data.articles here. If I would save this, my application works again because now I'm restructuring the data from where it should be restructured.

It's setting the API endpoints. It's either your Azure username for which you also need to set an API key or it is a public one for which you don't have to set an API key. You always have to set the content type, location, JSON. You need to append a body and the post request and the body includes the query. And the query is just the one that we used in GraphiQL. And then make sure to destructure the articles from the results because they're nested inside articles. And also if you go to the GitHub repo and you click show solution, you will find a solution branch. That is a branch inside the repo in which you can find the solution. So in here you can just go to the fetch function and find all the answers I just showed you. Let me open the chat again. Let's see where it is. If this solve people's questions, I see a problem occurred while processing your imports. I'm not really sure if it's related because I wouldn't really know why you are doing steps in import graphical because you don't have to do this. At this point. So maybe just send me a personal message. Paolo, with whatever you're trying to do because I don't think it's necessarily an exercise from, from this workshop. And then I see, Guillermo is getting a 401, an authorized message. Can you confirm you still have the error? Even if it's... Sorry? It's fixed now. I was missing the API key part of the string. I was sending only the key, but not the API key. Thanks. Yeah, it happened to me a lot as well. No problem there. So Paolo, if you want your question answered, please send me a personal message so we can continue with the workshop. Any other questions about this exercise number three? For this, you can use the chat again or mute yourself like Guillermo did and ask your question out loud. Okay, I will take it that's a no then, meaning that I will continue with the next exercise. So exercise number four. This one is quite similar to exercise number three, except this time we want to get a single article from Practical Dev. So if you look here, so this data now is coming from GraphQL, but if I click on any of these details, it will still get the data from the REST API. And for this of course, I also want to use GraphQL instead of using the REST API. So the steps I will do when I would try to fix this, I would first go to GraphiQL and figure out how to get a single article. For this you can probably, well go back to the list of queries and use the query to get a single article. The logic to get the ID from the URL is already inside the application. So you don't need to have the specific knowledge to do this. It's already there. But what I want you to do for this exercise number four is to get a single article using GraphQL. And for this you need to also make some changes in the code of course, probably in this component where you need to change this fetch function to get a single article. Now for this again, we can take 15 minutes. If people are going faster, it's fine, you can already go forward to the next exercise. But in 15 minutes we will do so one five, we will do the solution for exercise number four. If you get a 401, make sure to look at this right here, where you need to use your endpoints and then you also need to use the headers with the API key. Make sure to use these headers, which I sent in the chat, to get to your requests, and also make sure to never use the localhost endpoint because it won't work inside your code. If you want to explore the API itself, always use the localhost one. So, it might be confusing, it's something we are changing on Step Zen site, so for today, please, bear with me, while doing this. Okay, so what we were doing, was question number five, I guess. Yeah, question number five. So, what I like to do is, I would say, copy paste the whole block you had here. This part, so const fetch, copy paste it, and move it over to the article site. Because what we want to do, is for exercise number four, we want to query a specific article. We would place this, with this thingy. I still have the same GraphQL API, because the GraphQL API endpoint never changes. As we know as opposed to REST, we always have one single endpoint. We have a post method, we optionally have an API key. The thing that does change is our query, because we're getting a single article, instead of a list of articles. So to get a single article, you would take the ID of one of the articles, and then change it like this, let's say ID, and then put it in here. You can see it's expecting a string. If you would try an integer, you would get an error, because it's expecting a string. So this is one of the cool things that the GraphQL type system is giving to us.

10. Querying a Single Article and Using Named Queries

Short description:

To get a single article, copy and paste the query into your code and replace the hardcoded ID with a template literal. Remember to add a check to ensure structured data is returned. Unfortunately, there is no way to get all fields without specifying them individually. Named queries can be used for caching purposes and to handle multiple parameters. Use the query variables tab to define variables and pass them to the query using the name query. This makes it easier to structure queries and reuse a set of fields. Replace the hardcoded query with a named query and add a variables field in the body to pass the ID. Check for any rendering issues and ensure the React app is still functioning.

So this is the query to get a single article. So what I would do, which is copy paste it, I will go back to my code, and I will put it in here. And as I'm using template literals here, I could just take this value of id and put it in there, just like this. And then close it off. Save this. And then remember, like what we've done previously, we need to add a check here to make sure that we get these structured inflops. So we'll get a single article. So we do,.article. And then in here, we also inside the parentheses,.data,.article. We'll save this, and I will go back to my React app. Not sure where I left off. Made sure you stopped hearing me. At least you saw the screen. Any questions about this exercise?

Is there a way to get all the fields without write it? Like to get to the description, the ID, every field that is inside of the article?

Yeah. Well, first, unfortunately, there isn't. Okay. I think there is a proposal for the GraphQL spec, the latest spec, to have like a Select All, but currently, it isn't, because the main feature of GraphQL is making sure you select your fields dynamically. So there's probably a reason I left it out, but for now, there isn't a way. What you could do is using fragments, which will make it easier for you to reuse a large set of fields. We will be handling fragments later on. So we will be continuing on to exercise number four, number five.

So the query we previously used is a query parameter, which can be handled from a named query. And for this, what I will be doing actually instead is, I will just be doing this as a group, but it's probably easier. So for a named query, we can actually use the GraphQL first. So if you want to do a named query, the only thing you need to do is putting a name here. So you have the query, you have to operation type, this is query. You would use this as a keyword. And then you can just type your own query name. So you can, for example, call this get particle by ID. This will be a nice query name. And actually it often changes because it's only for you, for the eye, but if you're using a GraphQL client, as we're seeing here, you're often used for caching purposes. So this will become important later on, but they're also useful for something else. Because if you look here, we have this parameter hard coded, which is maybe not the nicest because maybe you have multiple parameters. Maybe you have Jason strings, maybe you have arrays at some point. For this, we have the query variables tab right down here. And in here, you can actually use Jason to type down your query variables. I will go take this part, bring it in here and use it as Jason like this. The way to pass it to the query to be able for the query to use it, we need to use the name query. Cause when we use the name query, we can also define variables here. What we can do is say there's a variable called id, which exists right down there, and it is of type string. And then this value is the input for this parameter. So it might seem like magic. Nothing already has changed here. What we have done though, is to make it easier to structure our queries. So now we have a named query that is using variables as a parameter. And then down here, I'm not sure why we have this issue, it's probably some rendering issue in graphical. But we're using a named query instead of a hardcoded. So if we would take this query and we would bring it to our editor, we can actually replace this query here as a query. What we can also do is we can add a new field in a body that's called variables, which is then a string of five version of this. And it will pass the ID in the same way as we see here. So basically it will do this. So this value will be transferred there. So you can actually use it inside your web code query. And then if we would go to our React app, things should still be working. Can I have error, let me see why, bad request. Request, let's see what's going on there. Reposting the payload. Repost the ID. Query twice. Sorry. Yeah, it's query, and then probably we need to omit the query within the payload. You see the beginning of the string. Yeah, I'm not sure, but we can try. No, so let me quickly see how to do it over here, because probably I forgot something, as I usually do. Um. I would press here. I see the same request. I can see I need to append a operation name. So probably the thing I was missing. What does this look like? Excuse me.

11. Using Named Queries and Query Storage

Short description:

In this exercise, we are using a named query to improve the code. We pass the variables in a more convenient way. Jago gives a helpful tip about hovering over a query in the network tab. The queries used at runtime are stored in the frontend app for future use.

Make myself a bit easier. This, see the query. I maybe need to append operation name here. Let's see if that will fix my issue. Turning this operation name. This, that's a comma there. And then save this again. Go back here, see if this resolves my issue. It looks like it didn't. So what else could I be forgetting? It's probably, ah. Looks like the variables are being... Maybe this doesn't need a stringify at all. Could be. I guess that's the reason. Because I'm already using ContentApplicationType.json. Probably don't really have to use a stringify. Yeah, so it looks like this is already better. And I should not forget to put the body HTML in there, which we have done in the previous. So now I'm using a named query, which you can see here. It's using a named query. And we're passing the variables like this, which is a bit nicer, but later on when we start using a GraphQL client, it becomes more important. It becomes more important. So Jago giving a nice tip. If you hover query in a network tab, you see all the text without needing to scroll around. It is smart. Let me see. So we run this. You can do this. Forget. Well, nevermind. So this was exercise number five. Any questions about using named queries? Just a quick question. Are these queries stored anywhere for documentation? How can you check the name of the queries that you created? Well, you don't really create them, you use them at runtime. But later on if we start using the vertical clients, they will be stored in your frontend app and then you will be able to use them later on. Oh, I see.

12. Fixing Filter Feature and Installing Apollo Client

Short description:

For exercise number six, fix the filter feature on the home page by using a named query and the 'tag' parameter. Update the fetch articles function in the home component to use the main query and pass the tag variable. Test the query in GraphQL before implementing it in the code. Skip exercise number seven to focus on exercise number eight. Install Apollo Client and GraphQL, the most widely used GraphQL client, for the next exercise.

And then for exercise number six, we're gonna be fixing an issue we had earlier on, or actually a feature we had earlier on. So if you remember, if we would go to the home page, we have this nice filter, but currently the filter isn't doing anything. We still get the same results. So what I want you to do for exercise number six is to use a named query for getting all the articles. And then I want you to use the, if we go to docs, I want you to use the parameter tag, here, parameter tag on articles to make the filters work again. It would go to the code to the home. You can see the value for filters here. So you need to find a way to pass the filter to the GraphQL query, and then use it in the query to get the articles for this filter instead of all the articles that are available at a latest time. So per request, we can take 10 minutes for it to make the fetch articles function in the home component also named query, pass the tag to it, so you can have some filters on the home page. So whenever you press the filters, the tag variable will be updated. So let's go back to the exercises. We were looking at exercise... Exercise number six. So the fetch articles function in source components home can be changed to use the main query. So if we go back to the graphical, we can... Change this one to maybe get articles and then use the articles here, and I guess it takes a tag parameter, so you can say tag... Is, let me just change this to tag, tag, tag. If we run this probably not much will happen, so there probably isn't a tag called 123456. There probably is a tag called GraphQL. You see this gives some nice, some nice results. You can probably also use TypeScript here. It should give us different results. Actually a article from mine, so it's kind of nice to see. So what we'll be doing, I've tested this now in GraphQL. So this is usually the way you go. We tried it out in GraphQL then you bring it to your code. I can just copy paste this and also make sure to change the name because if you have multiple queries with the same name that seems to be giving issues. Going to my home components. I'm going to update this thing here to use my new query. Of course, I also need to set the variables. And for the deck, I will take the filter prop which I have in my components somewhere. So I have a set filter probably here, somewhere. So this gets a filter prop. And this time it'll be passed to my components. But save this, I can go back to my application in here. And I can actually see the tabs are being added, the tags are working. So I have some React articles, I have some GraphQL articles. I have some TypeScript articles, including one for myself, which, well, in case you'd like to know it's how to set up zero-config TypeScript applications with Next.js. So you can see it all works. We can use the different filters. You can still click on an article to get some more details and all the requests are coming through GraphQL. Then I see a question from Vladislav. For some reason, article type graphical doesn't specify tag property. It has tags and tag list instead. Yeah, it could be because the parameter doesn't necessarily have to be a field on its own. I can call this basically anything I want. I can also call this input one or variable one because this is defined to my GraphQL schema and the text I use here doesn't necessarily have to be a field to there. The GraphQL schema itself will behave slightly different. Actually go in there and show you. So I have my query called articles and the rest API will take a parameter called tag, a bit like this. So the only thing that GraphQL API does is bringing this over to the rest API. But StepZenn automatically puts all the parameters as query parameters in there for you. So you don't have to do this manually but this is what would happen under the hood. Close this one. So this was exercise number seven or six, six. So exercise number seven is something we're going to skip actually make sure that we have sufficient time to work on the cool stuff. Because I can also imagine four hours might be too much for some people in here for multiple reasons. So we're going to be skipping exercise number seven but feel free to work on this exercise at home or anytime you actually have the time for it. What we will be doing now is we're going to go forward to exercise number eight. And for this I'm not sure if 10 minutes will be sufficient. So make sure to take 15 for it. For this we're going to be using Apollo Client as our GraphQL client. And there are multiple GraphQL clients Apollo Client is one of them. It is at the moment to most used one. They also have relay, which is also a great one but it's a bit harder to understand if you're new to GraphQL. So that's why we will be using Apollo Clients. Now, what you need to do for this exercise is install Apollo Clients and GraphQL. So this is the GraphQL front end library that will help you. That's actually a must have dependency for Apollo Clients. So you can install with MPM or Yarn.

13. Setting up Apollo Client and the Apollo Provider

Short description:

To set up Apollo Client and the Apollo provider, add the necessary code in the index.js file. Use the useQuery hook to fetch data in the home component. Refer to the Apollo documentation for more details. If you have any questions, feel free to ask. Take 15 minutes to complete exercise number eight. If you finish early, you can move on to exercise number nine.

You will need to add some boilerplate code in the index.js file to create an Apollo Clients. You will create a client and a provider. So it's pretty similar to as you have been using Redux maybe, in the past. You need to create a provider that will wrap your component tree with the information of the client. And this is to set up the clients. And then once you have to client set up from everywhere in your component tree, you will be able to use a use query hook. And for this, we actually will be going to the Apollo docs. We go here. And more specifically, we go here. Put this link in the chat. So what I'd like you to do for exercise number eight is we skip seven is install Apollo Client in the GraphQL library. Add the Apollo provider to the index.js file. Make sure to pass the header here as well with the authentication key in case you have any. Don't forget the API key in here. I will change it in the README as well. And then use a UseQuery hook for the home and article components. We're going to be replacing the fetch request with Apollo UseQuery hooks and the docs are right here. But it's a bit more advanced, it's a bit more coding. That's why we really need the 50 minutes. So make sure to take the 15 minutes. If you are done a bit earlier, feel free to go to exercise number nine already. Because I really want to make sure we have enough time for the people that need a bit more time. Exercise number eight, 15 minutes, so one-five. Okay, so feel free to continue finishing it while I'm running NPM install. So I'm going to be stopping my React app. I can run NPM install Apollo Client in GrubQL. Okay, so this is installed and then I can do NPM start to start my NPM server again. So what I will be doing for starters, I will go back here and I'll actually copy paste this code and bring it over to my source index.js file because I need to be creating a provider, very similar to how we do this with Redux or they're actually more tools that use providers. If you use the React context API, you might also know how this is set up in the imports here, I have a client, so this would be my components. Here would be my API key, something I can copy here. Then we can paste the, yeah. So I have my end points. I have my headers. You can see I don't need to set the content type header this time because, well, Apollo is a GraphQL client, so it already understands that GraphQL always needs JSON. So I don't need to set that one this time. So I have my client, and then what I need to do is I need to wrap my app components, actually, the app is doing all these kinds of things, in an Apollo provider. So this doesn't do anything yet. The only thing I've done so far is create an Apollo client, and then create a provider to which I'll pass the client. Any questions about this part? No? Okay? No? Okay. So then I will continue by going to the home component, maybe. And start putting in a Apollo use query here. So what I can do, I can say const data is await. Not sure, is it, no, wait. So use query. And then this is my query. Let me just start by doing this because I think it should work. Query, and then it will take some variables, which is this one. And then I guess I can delete all this. Let's see, use query. I think there, closing like this. Sorry, it's getting a bit messy, but we'll fix it in a bit. Zoom out a bit, a little bit more. So maybe just close this. So I'll do imports. Use query. I'm gonna do it in here. So it should be finding. So I actually also need to delete this part. So I can actually move all this up top. And I can use this as well. So I actually can delete this whole use effect function. Let's make it a little bit clearer what I'm doing here. So what I will be doing is I will take this whole user back function and I'll basically just delete it because we no longer need it. And we also no longer need to set the state because the poll will be running as far as this blog. So we're gonna be removing the article state. We're also gonna be removing this user back to reset articles when the filter changes. Instead, you're gonna be using this useQuery hook that we need to import, so import useQuery. We have data here. We have a query here, we have a filter, which is in the component and then we have the data and then as Vladislav said, it's a bit annoying that we need to do it like this because we actually we need to destructure this because articles is inside. But it's just the way GraphQL works and then this would already work.

14. Using Apollo Clients and the useQuery Hook

Short description:

When using the useQuery hook, you can get a loading parameter to check if data is still loading. The gql function helps transform a string into a GraphQL node. The useQuery function returns an object with loading, error, and data properties. You can also pass variables and other options as parameters. For getting articles and a single article, the process is similar. Use destructuring to access the data and handle loading states. Apollo Clients can abstract away imperative code and make data integration easier. It provides useful features like automatic state management and data fetching.

Although when our component first renders, we will get an issue here because articles isn't there yet. So what you can also get from the useQuery hook is a loading parameter, a loading return. We can say if loading returns something like this. If I save this, that can go to my, here we see what it looks like. We have done it correctly all in one so that we need to make some more changes. We probably have to argument a query. Ah yes, so I also need to use the gql function, which I can get from here, gql and I could pause this like here, gq, format this and go back. I should be getting data here now. I'm known, cannot read properties of undefined. Let me just, to be sure, do it like this. Let me just check this. Yeah, so now you can also quickly see the loading, loading thingy there, something you could make nicer, of course, but, well, not the main purpose of today. Besides loading, you can also get error from here, meaning that if the GrubQL API returns an error, you can use it somewhere else. So what I've done here is a bit messy, and it's something you can actually clean up. So instead of putting it like this, I can also turn this into a constant. I can create a constant here called getInStormArticles getInStormArticles is Stcql. And then I could just take this delete comma and put this thing in here. Format. And then we should be right again. So that still works. So this is how you would use a useQuery function. You can get an object in return with loading error data. You pass a query, which should be a valid GraphQL query, hence the GQL, which is basically a function that helps you to transform the string into a GraphQL node. And then we pass the variables here, which is the second param. And I guess there is more params. See variation variables. You can also pass any other options. Let me see if the text still works actually. Let me react. No, so I probably need to do is I need to click like this and call this, see it is better. So now it works. Okay. So that's how you do it for the get articles and then for the getting a single article. It's pretty much the same. We can leave this. We can delete all this. We can copy paste the code we had before. This time we're parsing a param which is ID. And this was params. D, maybe taking this GraphQL query. And we're going to create constant for it again. So const get article by ID like this. Go on. You can also delete new states. It's not setting state. I need to replace this with this. And then, of course, I also need to import these things. Then in here, I need to set data, not data but article. I can also do a const this, it's easier. And now if I will be clicking on an article, I should be getting the article again. So pretty similar, we're again using loading data. We don't use the error just yet. If stuff is loading, just return loading. If stuff has finished loading, so this is all synchronous, we'll go from top to bottom. So we can destructure article from this thingy here and then get all these variables, see if they exist. We got to delete quite some code. So actually, could delete all the set state functions because this kind of state is being set by a pull. We don't need to set it by hand anymore, which is quite nice. You get quite some code for free, which is something I usually like. And as Vladislav said, it's a bit annoying that you have to destructure it like this. But I mean, we had to do the same thing previously already when we destructured the results from the REST API call, and we need to get the result from data.json. And then we already had to get his data down the stream. So yeah, it's something you could use, too. In the end, it's only one time destructuring, while with REST, you're maybe doing infinite amount of destructuring. But yeah, that's using Apollo Clients. Any thoughts about using Apollo Clients? Do we like it? Do we dislike it? If you didn't have the time to form an opinion on it, that's also fine. It's maybe your first time interacting with it. And yeah, it's like the nice thing is it will really abstract away those things that you would otherwise have to do imperatively by hand. So it's kind of nice it does all these things for you. You could probably also imagine that, if your application grows, if your front end project might be a bit confusing at some point, or it's hard to tile the data together, useQuery might not be your best option.

15. Using client.query for Manual Updates

Short description:

You can use the client.query method to query the client directly, without any state updates. However, you would need to handle the updates yourself. This was exercise number eight.

What you can also do instead is, and this probably will give you a bit more handles that you can poke yourself, is you can still use and use effect like this. This effect. What you can do in here is, you can still get a data variable. So what you can also do with constant data is client.query. For this, you would need to import the clients from here. So we need to export it. And here, you could import client from there. And then you could query the client directly in the same manner. And if you do this, you don't have any state updates. So you need to make sure you do the upstate updates yourself. You would need to put, like I said, something. You would need to put data in there. You would need to check for updates. So it's maybe the rameshot id changes. So there's tons of things you use queries doing for you that you could also do manually by hand. But that's up to the user developer, of course. I usually like to tell people how to use this query. You already know how to do it in a fetch request, so then you have different ways of approaching this. So this was exercise number eight. And then we have three more exercises to go. So we might be able to finish in time, which is nice.

16. Using Mutations and Adding Upvotes

Short description:

In exercise number nine, we will learn how to use mutations in GraphQL to update data. We will add upvotes for every article and use the upvote article mutation to upvote an article based on its post ID. The upvotes are stored in a Firebase database. You can try this out in the GraphQL playground and see that mutations work similarly to queries. For exercise number 10, we will use the useMutation hook from Apollo to handle the upvoting functionality.

For exercise number nine, we're gonna be looking at mutations. So we already learned that we can use QueryQL to query data. So what we will be learning now is how to use QueryQL to mute data, meaning that you can update data, instead of just reading it. And for this we will be using mutations. So, exercise number nine is a bit, it requires quite some React coding skills. So yeah, I would propose to just don't do this. And instead go directly to exercise number 10. But first, we want to add the up votes for every article. To the screen. So our query here also has a value for up votes. That we also want to use here, so maybe we can do it in similar fashion as we have here. And then the left. What is the label style? We can do. So please code along. So inside home.js, you have your query for getting articles. In here, you need to add a new field called up votes, and then going down, whenever you destructure the articles, you need to destructure upvotes there as well. Then you can just put it in a span to display it. Saving this, I will be seeing up votes here. These are my up votes. You can see there's zero everywhere because we haven't up voted any of these articles yet. If we would go to our Excise Number 10, you can add a button to upvote an article. For example, by using the mutation called upvote article. We would go to the graphical. We can use this to get articles. Just get all articles. We don't really need to tag anymore. We want to get the articles, we want to get the ID and the number of upvotes. If I just former me, everything has an upvote called upvote with a value 0. We want instead we want to use a mutation to upvote an article based on their post ID. So next to the query, we can also add a mutation. We can name this upvote article. We can add mutation here. We can type upvote article. We need to set the post ID. I'll just do it manually now as it doesn't really matter. Article here. I like this. So this reputation to upvote an article and then GraphQL will ask us which thing we want to use. Article and as you can see, it gives me a return. So now we're in get articles again. You can see the upvotes are there and either this duplicating or someone else is trying it as well. I'm gonna be assuming someone else is trying it as well. The same here, I'm gonna vote a different article and then get the list of articles again and I see the upvote of one there. So this is all being stored in a Firebase database. I told you before I use StepStem to get the practical dev API, but I also use it to connect the Firebase database. So what we'll be doing is we're storing a combination of post IDs and a number of upvotes in this Firebase database. For you it doesn't really matter as I already created this API for you. Retrieve this again. So yeah, please go to your graphical and try this out. Try out this upvote article. See if it works for you. And then you also get a feeling with the test and see that they are very much the same as using queries. We can use the name set up similar as we saw before. So we can make this post ID should be a string. We can set a query variable here saying post ID is a string. It is specifically this string. And then here we would say this is post ID. And it would still work as expected. So yeah, any of the folks, anyone in this group is doing will also show up here. So if you see strange numbers, maybe something increases bit more than you thought it would, it's probably someone else doing the same upvote because it's all being stored in the same database. So what we're going to be doing for exercise. Exercise we're at. Please go away with this zoom handlebar. Exercise number 10. You want to be using a use mutation hook from Apollo to do this. And the use mutation hook is quite similar to the hook we saw before, which was the use query hook. I put this link in the chat as well. It's quite similar. So we have a use mutation hook here and we can use it whenever we click a button. There it is in the chat.

17. Adding Upvote Button and Mutation

Short description:

To add an upvote button to the home component, you need to add a useMutation hook and a button with an onClick event. The useMutation hook returns an array with an update function. You also need to create the mutation using the GraphQL query from GraphiQL. After adding the button, you can test the upvote functionality by clicking it. If there are any issues, check the network tab for errors.

So if we will be going back to our code. We can go to the home component for example. And we should be adding a use mutation hook here. So at use station here. As it also returns data. You might need to rename the returns. The use mutation. Something else so probably you would need to do. Probably you would need to do const loading errors data, use mutation, maybe something like this. You probably need to be renaming these loading mutation. Error mutation data. You probably need to be renaming those similar like this because we're going to be using two hooks in here. And then in here, you would like to set a button to probably upload. So maybe, add the upload button there. Add the upload button there. So there's a couple of things you need to do. You need to add a mutation. You need to get a response. You maybe need to add an upvote. You also need to add an upload button. And this will upvote the articles whenever you click it by using whatever the mutation returns. Let me see if the upvotes are working here just to be sure we're not going crazy. Go to article, shows there. Get articles, shows there. Okay, so API-wise it should work. Let me go to the codes. See why it might not work. So for starters, we need to get a use mutation function here. First import it from Apollo Client. Use Mutation. And then the return of the use mutation is slightly different from what we saw before. So it actually returns an array with an update function. So this is update function, you can call it whatever you want because it's an array. And then the second part is the objects we saw before. Then it goes to the right. So use Mutation. It will also take a query, and it will actually only take this variable here. And, of course, we need to create our mutation here as well. Going to be going back to GraphiQL, going to be taking this one here. And what I can do is say const the PhotoArticle, this thingy. And then close with the template literal. It's the one. And use this thingy in there. Going like this. Look something like this. Figuring my app shouldn't break right now. Yeah. And then if I have this update function here. So let me create this button. Zooms into... button. Stick a title. Tap on it. and say on click. Let me stop what I'm clicking. So we're going to be... using this update function and we're going to be passing the variables to it. Button is complaining because it's not being closed. Save this and see a tiny little button like this. And say upvote. Yeah, so now I'm seeing an upvote button. So let me see if we can find Vladislav's issue of the network tab. So I'm going to be clicking, let me just scroll down. Music Monday. Upvote. Operation, we have a post ID. And I think I see the issue there. Refreshing this. No, I don't see it updated. I guess it is because, and it's weird because we should see an error for this, it is supposed to be a string.

18. Fixing String Issue

Short description:

We need to make sure this is actually a string. Let's pass this string and refresh the page. It should be working better now.

But somehow this still works, so that is super weird. Maybe we should do it like this. That is weird. Sorry for that. So what we need to do is we need to make sure this is actually a string. So how do we do this? Ah, we do it like this. This probably is done. This should be working better. Let's pass this string. And if I refresh the page, it is showing a fault one. Now this is supported. Yeah. Happy to have solved that. I will look into the issue because it should, GraphQL should actually be finding this error and make us aware of it. Maybe it's because of how... We do this. Wow. Something to figure out later.

19. Automatic Data Updates and GraphQL Code Generator

Short description:

Exercise 11 involves using the refresh queries option to automatically update the data whenever an article is uploaded. By defining an object of the query or referencing the name of the query, you can refresh the queries and see the updated values. Additionally, the speaker mentions a library called GraphQL code generator, which generates TypeScript types based on the GraphQL schema and operations. This can save time and effort when using TypeScript in a project.

Any questions about this exercise? Sorry, I'm bombarding with questions. But another one, I would have... You can hear me, right? Yes, I can hear you. Yeah, I'm just... I was curious, for example, what would I do if I want to see uploads without refreshing the page? Yes, that's a good question. And I think it's the next exercise. Yeah, it's the next exercise. So what we could do, actually, maybe we can do this exercise 11 together. And then we would have some time for Q&A and round up. It's okay with everyone. Yeah, that's cool. Okay, good. Alright. So let's do that. So exercise number 11 is, every time you upload an article account, you'll be updated. For this, we're gonna be using the refresh queries option. And this is a option using all these. It could actually use this loading button here as well by the way. What we do is go to that box here, this is an option which is very useful and maybe say... So what we'll be doing for these exercises is whenever you... press any of these buttons... it's not working perfectly because what I wanted to do is change this into a separate component. So now it's showing loading everywhere. It's a bit annoying but it can be fixed by refactoring how the components are structured. But I wanted to skip this for today to make it not too overwhelming. So this mutation here will take an... an object here, which you can do a... refresh queries. And in this refresh queries, you can actually pass the queries you want to refresh whenever you run the use mutation. So it will take the variable we created up here, which has our query. And then now we've saved it. I will do this, we need to refresh the page. It's refreshed and you can see the value updates. There's a minor lag in it. It probably... React. So maybe the test API I'm using is getting a bit overwhelmed. More requests. Maybe we're just doing too many requests. We both did a minor lag. You can see going up now every time we press. Every time we press, it's by using the ReFeTcH queries option. There are two ways to do it. You can do it this, by defining an object of the query, and I'm guessing this way, you can also pass variables to it in case you only want to get the subset of the articles. Or you can just reference the name of the query like this. So get articles is the name of this query. You can just reference it like this, save it, refresh just in case. And then it should be working as well. So, yeah, that's how you would automatically get the new data whenever you change something. And I guess this was the final question we had for the introduction part. I usually do this just like a full day workshop. And like I told you before, I'm also turning this into a course. So scroll down for the form. You can drop your email address in case you want to learn more about the course later on. And here's the link again in case you want to be updated. Something else I wanted to show you is called GraphQL code generator. And this is part of the full day workshop, actually, that I do. It is a cool library that helps you to generate typescript types based on your GraphQL schema. And so if you would have GraphQL schema and a set of operations, which are the queries that we have in our app and the plugin in which you define what you want to generate, you can generate all these GraphQL types based on your schema automatically on build-time. That is kind of cool, because if you're using typescript in your product, there's a way you don't have to type all the functions and variables every time you make a change. This is the final thing I wanted to add to today's workshop, so thank you. And well, I hope to stay in touch, and I hope you enjoy the conference as well.

Watch more workshops on topic

React Summit 2023React Summit 2023
170 min
React Performance Debugging Masterclass
Featured WorkshopFree
Ivan’s first attempts at performance debugging were chaotic. He would see a slow interaction, try a random optimization, see that it didn't help, and keep trying other optimizations until he found the right one (or gave up).
Back then, Ivan didn’t know how to use performance devtools well. He would do a recording in Chrome DevTools or React Profiler, poke around it, try clicking random things, and then close it in frustration a few minutes later. Now, Ivan knows exactly where and what to look for. And in this workshop, Ivan will teach you that too.
Here’s how this is going to work. We’ll take a slow app → debug it (using tools like Chrome DevTools, React Profiler, and why-did-you-render) → pinpoint the bottleneck → and then repeat, several times more. We won’t talk about the solutions (in 90% of the cases, it’s just the ol’ regular useMemo() or memo()). But we’ll talk about everything that comes before – and learn how to analyze any React performance problem, step by step.
(Note: This workshop is best suited for engineers who are already familiar with how useMemo() and memo() work – but want to get better at using the performance tools around React. Also, we’ll be covering interaction performance, not load speed, so you won’t hear a word about Lighthouse 🤐)
React Advanced Conference 2021React Advanced Conference 2021
132 min
Concurrent Rendering Adventures in React 18
Featured WorkshopFree
With the release of React 18 we finally get the long awaited concurrent rendering. But how is that going to affect your application? What are the benefits of concurrent rendering in React? What do you need to do to switch to concurrent rendering when you upgrade to React 18? And what if you don’t want or can’t use concurrent rendering yet?

There are some behavior changes you need to be aware of! In this workshop we will cover all of those subjects and more.

Join me with your laptop in this interactive workshop. You will see how easy it is to switch to concurrent rendering in your React application. You will learn all about concurrent rendering, SuspenseList, the startTransition API and more.
React Summit Remote Edition 2021React Summit Remote Edition 2021
177 min
React Hooks Tips Only the Pros Know
Featured Workshop
The addition of the hooks API to React was quite a major change. Before hooks most components had to be class based. Now, with hooks, these are often much simpler functional components. Hooks can be really simple to use. Almost deceptively simple. Because there are still plenty of ways you can mess up with hooks. And it often turns out there are many ways where you can improve your components a better understanding of how each React hook can be used.You will learn all about the pros and cons of the various hooks. You will learn when to use useState() versus useReducer(). We will look at using useContext() efficiently. You will see when to use useLayoutEffect() and when useEffect() is better.
React Advanced Conference 2021React Advanced Conference 2021
174 min
React, TypeScript, and TDD
Featured WorkshopFree
ReactJS is wildly popular and thus wildly supported. TypeScript is increasingly popular, and thus increasingly supported.

The two together? Not as much. Given that they both change quickly, it's hard to find accurate learning materials.

React+TypeScript, with JetBrains IDEs? That three-part combination is the topic of this series. We'll show a little about a lot. Meaning, the key steps to getting productive, in the IDE, for React projects using TypeScript. Along the way we'll show test-driven development and emphasize tips-and-tricks in the IDE.
React Advanced Conference 2021React Advanced Conference 2021
145 min
Web3 Workshop - Building Your First Dapp
Featured WorkshopFree
In this workshop, you'll learn how to build your first full stack dapp on the Ethereum blockchain, reading and writing data to the network, and connecting a front end application to the contract you've deployed. By the end of the workshop, you'll understand how to set up a full stack development environment, run a local node, and interact with any smart contract using React, HardHat, and Ethers.js.
GraphQL Galaxy 2021GraphQL Galaxy 2021
140 min
Build with SvelteKit and GraphQL
Featured WorkshopFree
Have you ever thought about building something that doesn't require a lot of boilerplate with a tiny bundle size? In this workshop, Scott Spence will go from hello world to covering routing and using endpoints in SvelteKit. You'll set up a backend GraphQL API then use GraphQL queries with SvelteKit to display the GraphQL API data. You'll build a fast secure project that uses SvelteKit's features, then deploy it as a fully static site. This course is for the Svelte curious who haven't had extensive experience with SvelteKit and want a deeper understanding of how to use it in practical applications.

Table of contents:
- Kick-off and Svelte introduction
- Initialise frontend project
- Tour of the SvelteKit skeleton project
- Configure backend project
- Query Data with GraphQL
- Fetching data to the frontend with GraphQL
- Styling
- Svelte directives
- Routing in SvelteKit
- Endpoints in SvelteKit
- Deploying to Netlify
- Navigation
- Mutations in GraphCMS
- Sending GraphQL Mutations via SvelteKit
- Q&A

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

React Advanced Conference 2022React Advanced Conference 2022
25 min
A Guide to React Rendering Behavior
React is a library for "rendering" UI from components, but many users find themselves confused about how React rendering actually works. What do terms like "rendering", "reconciliation", "Fibers", and "committing" actually mean? When do renders happen? How does Context affect rendering, and how do libraries like Redux cause updates? In this talk, we'll clear up the confusion and provide a solid foundation for understanding when, why, and how React renders. We'll look at: - What "rendering" actually is - How React queues renders and the standard rendering behavior - How keys and component types are used in rendering - Techniques for optimizing render performance - How context usage affects rendering behavior| - How external libraries tie into React rendering
React Summit Remote Edition 2021React Summit Remote Edition 2021
33 min
Building Better Websites with Remix
Remix is a new web framework from the creators of React Router that helps you build better, faster websites through a solid understanding of web fundamentals. Remix takes care of the heavy lifting like server rendering, code splitting, prefetching, and navigation and leaves you with the fun part: building something awesome!
React Advanced Conference 2022React Advanced Conference 2022
30 min
Using useEffect Effectively
Can useEffect affect your codebase negatively? From fetching data to fighting with imperative APIs, side effects are one of the biggest sources of frustration in web app development. And let’s be honest, putting everything in useEffect hooks doesn’t help much. In this talk, we'll demystify the useEffect hook and get a better understanding of when (and when not) to use it, as well as discover how declarative effects can make effect management more maintainable in even the most complex React apps.
React Summit 2022React Summit 2022
20 min
Routing in React 18 and Beyond
Concurrent React and Server Components are changing the way we think about routing, rendering, and fetching in web applications. Next.js recently shared part of its vision to help developers adopt these new React features and take advantage of the benefits they unlock.In this talk, we’ll explore the past, present and future of routing in front-end applications and discuss how new features in React and Next.js can help us architect more performant and feature-rich applications.
React Advanced Conference 2021React Advanced Conference 2021
27 min
(Easier) Interactive Data Visualization in React
If you’re building a dashboard, analytics platform, or any web app where you need to give your users insight into their data, you need beautiful, custom, interactive data visualizations in your React app. But building visualizations hand with a low-level library like D3 can be a huge headache, involving lots of wheel-reinventing. In this talk, we’ll see how data viz development can get so much easier thanks to tools like Plot, a high-level dataviz library for quick & easy charting, and Observable, a reactive dataviz prototyping environment, both from the creator of D3. Through live coding examples we’ll explore how React refs let us delegate DOM manipulation for our data visualizations, and how Observable’s embedding functionality lets us easily repurpose community-built visualizations for our own data & use cases. By the end of this talk we’ll know how to get a beautiful, customized, interactive data visualization into our apps with a fraction of the time & effort!