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.

What's included:

1. Getting started with GraphQL

2. GraphQL Queries

3. Mutating Data

4. GraphQL in React

5. Using a GraphQL Client

113 min
07 Dec, 2022

AI Generated Video Summary

Today's workshop focuses on GraphQL for front-end developers. It explains the advantages of using GraphQL over REST APIs, such as having a single endpoint and flexible data structures. The workshop covers topics like running queries, using relational fields, setting up the GraphQL API, and using Apollo Client. It also introduces mutations for updating data and automatic data refresh using the Refetch Queries option. The workshop emphasizes the use of GraphQL Code Generator to generate TypeScript types based on the GraphQL schema.

1. Introduction to GraphQL for Front-end Developers

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 projects. We will be building a front-end project that uses GraphQL as its API. I work for StepZen, a GraphQL-as-a-service company. I also give workshops and trainings through my own company, Hack Team. In this workshop, I'll show you why GraphQL might be a better alternative and how you could use it in your projects. Let's have a look at a REST API first. One common trait of a REST API is that they have multiple endpoints. If you're building something that should be future-proof, a REST API might not be the best choice. REST APIs can be used together with GraphQL, but GraphQL offers better features.

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 projects. And also, most of the time you will be spending inside a project. So we're building a front-end project that is using GraphQL as its API.

My name is Roy. I am... Well, most of all, I'm a 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 through my own company, Hack Team. 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 with the handle, EdcatHackTeam. So 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 or fiddling with GraphQL. Maybe you'd like to learn more about all the GraphQL technologies out there. So that about me. Back to today's topics. What are we going to be handling today? It is GraphQL. You can only use GraphQL if you also have a GraphQL backend. So part of what you have to 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 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. And what we will be building is the frontend part, so the interaction with the GraphQL API, how to get data out 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's workshop. And I've set up a web page 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, that'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. First of all, you need to go inside the introduction directory. So I just send you the link in the chat. Everyone should have it now. In this repo, you can find all the materials. You can also find solution branches that contain the solutions for the exercises we'll be doing today. And this is for yours to keep, so 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 link's here on the screen, but it's also on 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 it compares to REST APIs. Because people actually like to say 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 then with better feature projects, or maybe your team that you're working with, because most of all technology is being built by people. And 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.

One common trait of a REST API 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 prediction-grade with REST APIs, you might even have like a hundred endpoints or more. So suppose you'll be working on this great project, and I'm going to start with an example. Suppose you start working on the e-commerce platform of the future. So maybe you get a proposal by a recruiter, or maybe your manager comes to you and tells you you're going to be building the e-commerce platform of the future. And this future e-commerce platform has a command like this stack. So you have a database, you have a REST API, you have a React application, and it's also using JavaScript. Maybe there's already some logs being created for this project, as you see on the left. It will have maybe a mobile page which you can find the specific product, 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 are 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. Well, of course, the REST API as today is a GraphQL workshop, of course, it would be weird not to have something against the REST APIs. So I'd be saying if you're building something, it 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.

2. REST APIs vs. GraphQL

Short description:

REST APIs have multiple endpoints and fixed data structures, causing the need for multiple requests and filtering of unnecessary data. GraphQL solves this by having a single endpoint and flexible data structures. With GraphQL, developers have control over the data being returned. A GraphQL request is similar to a curl request to a REST API, but with a POST method. Queries are used to retrieve data, while mutations are used to mutate data.

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. 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 big, I would say always try and use TypeScript, well, for many different reasons. And that's why I also will be introducing some TypeScript later on at the end of this workshop.

So being a brave developer you are, you just start building with this REST API. And let me explain 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 maybe comes from a slash product slash endpoint page, 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 maybe also want to show like, 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 example, for this product. So that's already three endpoints that you might be needing. And you may be even need more endpoints, right? But 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. That's what probably also need another API endpoint in order to calculate this. So typically with REST API's, 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 trait of REST API's. REST APIs also will return fixed data structures. It is a second trait of REST API's.

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 would probably have it's own endpoints and then return 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, they 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 for the 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 your database table. And of course there are things you can do to optimize 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 will lead 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 a price while the products endpoint 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 a 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 and points that show maybe sales or discounts and points 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 to fix data structures, which is a common trade of GraphQL for 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 does 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 transported 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. And I will explain to you why it's always a POST request, because with GraphQL, as we have a 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.

3. GraphQL Operations and Schema

Short description:

GraphQL simplifies the process of mutating data and supports real-time data through subscriptions. A GraphQL schema defines the structure and operations of the API. To retrieve data from a GraphQL API, you send a GraphQL document containing a query with specified fields. The response is always in JSON format and has the same shape as the query. If you have any questions about GraphQL, feel free to ask now. The implementation will be on the front-end side, and you can find all the resources in the GitHub repo. Clone or fork the repo to get started.

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 PUT or PATCH. But you can also delete data. So this will be similar to a DELETE method. So GraphQL actually simplified all these different ways of mutating data that you might be used to for other HTTP formats.

And then there is 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 stop tracker, you want to be using subscriptions. And we won't 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.

And 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, the 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 a complete schema but at least a 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 are also operations defined. So this operation will have three different types, its product, review and offer. And it will have 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 possible queries in here and all the different types are set by type products, type review, and you also have relationships between types.

And then to get the information of a GraphQL API based on its 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 the product, you are giving it a parameter, which is number three. So this is number three product ID, and then you're defining all the fields that you like to see returned. So these are title, thumbnail, also some relational fields, like the account of the number of reviews and also the average rating for all the reviews. Besides that, you can see we also are getting information about offers like a reseller and a price. So this will be a scheme that will 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 revenues and all the data you like to be returned. And then the response of the GraphQL API will always be jason. So it's important to remember, the response is always jason. 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, a thumbnail, we have related data. So it's a predictable return result. It has the same shape and structure as the query that you send to the GraphQL API. I hope this sounds very clear. 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 already before we dive into any examples later.

The implementation of today will be… Well, not this, 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. In here you can find all the exercises we will be doing today and also some general setup instructions. We will 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 all the resources. In here you can find a simple project setup. We have a package.JSON to set up the Next.js. I think it's Next.js. I guess I just create a drag to set up the front end app. We also have a step set directory. This is where the GraphQL API lives. And as I told you earlier, you don't have to make any changes to this GraphQL API at all. This GraphQL API is just there to help you build 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 the repo later on, you might lose the information in here. So make sure to fork it as well.

4. Setting up the Project and Introduction to GraphQL

Short description:

To get started, clone the repo and navigate to the introduction directory. Run 'npm install' or 'yarn' to install the dependencies. Open the readme file in your editor and follow the setup instructions. Start the development server and you'll see the application we'll be working on. It currently uses a REST API, but we'll be implementing GraphQL instead. We'll add features like filtering, pagination, and upvoting. We might also convert the app to TypeScript. In the Steps directory, you'll find a mock GraphQL API using the practical dev API and a Firebase database. Run the GraphQL API in a separate terminal window by installing StepStem and running the CLI.

That way you are certain that you will have this information for a while, as long as you keep your Gitter 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 we will have this code thingy. And if you would copy this, you can copy the... 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, you can just type git clone. Clone. And then append this address and it will clone the repo for you. I'll put this command in the chat, for people that maybe aren't that familiar with using git clone. So if you're using git clone like this, you would get a local copy of the repo on your machine.

And then you would have to cd into the introduction directory. So after cloning, let's assume you've done this, 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 advanced 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 root, which contains both the introduction and the advanced section of today's workshop. And we probably will be able to finish the introduction part, which we won't be able to finish the advanced section as well. But as you have to repo, make sure to clone it and fork it and then you'll 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 would 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 project 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 projects. So let's continue from this part on.

Inside the introduction directory, you can also find a readme. And 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. We go in here, I can find the readme and the introduction directory, which includes the setup instructions, which I just walked you through. We can do npm install, and then we do yarn. And then 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 projects. And it will show the application we will be working with today. So you would see this application. It is indeed a bit of a 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. It's not data from hacker news, but it's data for 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 detail page by 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. If I go back to the README, you can see we have this set up. And then we can go to exercise number 1. 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. And 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 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. 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 its new terminal window, I need to make sure that I am in the introduction directory. And then there I just run NPM install globally StepStem. So this will install StepStem, which is a GraphQL service that allows you to create GraphQL APIs declaratively. And I already set up a GraphQL schema with StepStem in here. So I don't need to make any changes to that. The only thing we need is install on 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 that is also inside this repo.

5. Setting up the GraphQL API

Short description:

To set up the GraphQL API, install the CLI and optionally sign up for a free account. Running 'steps and starts' will deploy the GraphQL schema and provide a local host endpoint or a production-ready endpoint. Ensure that everyone can access the GraphQL API in their browser. This API will be used for the rest of the workshop. Now that the setup is complete, we can start building and using GraphQL in a front-end app.

So 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 as one caveat, if you use a public account, your data will be deleted in like 14 or 30 days. So if you want to 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, that'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 want to continue with a public account, or you want to sign up for a free accounts. To run the GraphQL API, the only thing you need to do is run steps and starts. So this will take the 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 with a graphical 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 ACDPS and then public with some random string. You can open that one in the browser as well. So if I would be opening that one. If I would be opening this in a browser, I can see a graphical that looks something like this. So this is the old version of GraphQL. There also is a new version. See if I have it somewhere, news app. So this is what you would be seeing if you are using a public account. You would be seeing the newest graphical and for signed up accounts, we're in the process of making the latest graphical available for signed up accounts as well. So just to check in, is everyone able to see the GraphQL API in their browser? So either on a local host endpoint or on a public endpoint. 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 setup 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, 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 we just need one more person to verify that they are, they have the GraphQL API set up. And I'm going to 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. Okay. So I guess that's done now. Great. Okay. So we can continue. If you go back to a README, you have cloned the repo. You have installed all the dependencies. You have installed the steps in CLI, which we need to run the GraphQL API. And now I'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 using GraphQL in a front-end app.

6. Running Queries and Adding Fields

Short description:

For exercise number one, run your first query to retrieve the fields ID, Title, and Description of the articles from the GraphQL API. Use the articles query and specify the fields you want. You can find the available queries in the GraphQL documentation. For exercise number two, add the username field to the query to get the username of the user who wrote the article. Take five minutes to make the changes and we'll go through the solution together. Feel free to work ahead if you're already familiar with GraphQL. The exercises are available in the repo.

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 does 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 GraphQL.

So GraphQL is the explorer that you're seeing here. Whenever you open the endpoint that you see in your terminal, whenever you do random steps and start. So it's either the local host one, or it is the production-ready endpoint, which either starts with your username or starts with public and then some random string. But for exploration, I would say, open the local host because it's made for exploration and you will get a GraphQL. So it's either the old version of GraphQL or the newer version of GraphQL, which is this one. In both versions of GraphQL, you can find the schema by clicking on Docs. And 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. But for this first exercise, I want you to retrieve the articles and then take the fields 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 steps and I graphicalize 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. 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 upvotes. 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 GraphQL you can follow the same steps, go into query and then, I don't know, take any of these queries. So, 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 I will be doing here, whenever I want to do a operation, I just start typing the operation type before. So I will be typing query to let GraphQL know that I want to send an operation that is a query. And then I open this query using the curly brackets. And then here I need to define the operation name. So it's not the 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 it confined 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. So I see here, which I can just type like this. You can see there's also this nice auto-completion coming from GraphQL, 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 won't 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, I'll click on the article because article is a response type. And if I want the ID, I see you can just type ID. I already see that ID is of type integer, doesn't really matter right now, but it's useful to know later on. You can type ID. Again, you have the auto completion, which is quite nice. If we scroll down, we can also find the title properly, so the title is also type. It's of type string. I have title here. And then the final field I want is description. And I can see description is also in here. It's also a string. You just start to have a description. So this is my query. And I can use it to retrieve the id, title, and description of all the articles of Practical Dev using this REST API that I have running now through the repo we set up in the beginning. As I press play here, I will get a list of all the articles. And as you can see, these are 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 GraphiPol, which should give me the same results. But this is basically everything you needed to do for exercise number one.

So a quick check-in. Is everyone okay right now? Does 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 marks. So we're going to 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 GraphiPol, 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 exercises are a bit slow to you if you already are 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 that article? And for this, it 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 and vary you can see if you click on docs, you can find all the different queries.

7. Using Relational Fields in GraphQL

Short description:

To retrieve user information in the articles query, use the user field and select the username. This allows you to see who wrote the articles in Practical Dev. Relational fields in GraphQL can come from different database tables. As a developer, you can easily use this data regardless of its source.

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 and if you click on it you see it has a response result type of its own that is not a string. So it's a, what we call a custom scholar or a 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 the sub selection of fields for user. And then here we can start typing username and it should get us the username for this user. Then we can see whoever wrote these articles in Practical Dev. 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, GraphiQL did it for us. So I see Jago 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 GraphiQL because if we have this, we have this other completion so it will help you do these kinds of smart things. This is how you would use relational fields. And in this, in the case of Practical Dev this is all coming from one REST API, but maybe if you are 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 a user table, 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.

8. Using GraphQL API in the Application

Short description:

In this exercise, you will replace the REST API with a GraphQL API in your application. You will need to swap out the GraphQL API endpoints and set the method to POST. You may also need to add headers, such as the content type and authorization key. Take 15 minutes to complete this exercise and ensure that everything renders correctly. Remember to add the authorization header if you signed up for an account. You can refer to GraphiQL for pointers on how the HTTP request is sent. Once you have made the changes, check if the GraphQL request returns the expected data and update the code accordingly.

So circling back to the readme and 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 use the inside the exploration tool, now we will use it inside our application. So we have the graphical here. So we're going to be using this query inside our application instead. So what you will 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 intelligence things, or maybe, maybe, Adam could be anything. And maybe you're one of those Vim 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 will need to open the homepage components. In the homepage component, you can find a fetch function that is getting the information from the Practical Dev REST API. So the information you're seeing here, sorry, here, this information is all coming from this fetch request. But as you can see here, 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. A bit like this. Or if you're using a public endpoint, it should be something like this. Public, and then some random string. Oh, usually it 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. What's important to know here, never use the localhost endpoints. Localhost endpoints, as it won't work. So you want to use the GrafQL 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 actually give you a way, just to make sure that we don't get confused about this. You always need to set the content type to JSON because GrafQL APIs only work with JSON. And then if you have signed up for a Steps and Accounts, you also will need to add your authentication key here. So you need to type authorization, and then you would need to type API key. Yeah, that's the API key. And then if you have this, you will 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 endpoints. 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 tapping GraphiQL to get any pointers to how the HTTP request is actually being sent. Come back a bit earlier, I see some interesting questions. Why everything is a post method? 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 it query, and this will be a string that contains this. But probably as I have a multi-line so 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 make sure to never use the local host, does it not work. I've set my method to post. I've set my headers which are the authentication key in case you need one. And I also set the content type, application JSON. And then in a buddy, I append that the query I want to use. So it would save this and I would go back to my app. I would probably store, I would refresh this because the data format from the GraphQL API is a little bit different. Spec here, so we do request succeeds. So I have a GraphQL request, returns my data. I can see the data's here, but as you can also see is the request from the rest API was different, and our data's 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.

9. Fetching a Single Article with GraphQL

Short description:

To get a single article using GraphQL, make changes in the code, probably in the component where the fetch function is located. Copy and paste the GraphQL query to get a single article and replace the ID with the desired article's ID. Remember to use the correct API endpoint and headers with the API key. We will spend 15 minutes on this exercise before moving on to the next one.

If I would save this, my application works again, because now I'm destructuring the data from where it should be destructured. So it is setting the API endpoint. It either has your 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, hence the post request, and a body includes the query. And the query is just the one that we use in GraphiQL. And then make sure to destructure the articles from the results because they are nested inside

And also if you go to the GitHub repo and you click show solution, you will find a solution branch. So this 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 step send imports 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 this workshop. And then I see Guilherme, is getting a 401, an authorized message. Can you confirm you still have the error? Yeah, 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 for things. Yeah, it happened to me a lot as well. No problem there. So Paulo, 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 could use a chat again or unmute yourself, like Guilherme did and ask your question out loud. Okay, I will take that it's a no then, meaning that I will continue with the next exercise. So exercise number four. This one's quite similar to the exercise number three, except this time we want to get a single article from PracticalDev. 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 will try to fix this, I would first go to graphical and figure out how to get a single article. For this, you could probably go to a page or use a 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. What I want 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. And 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 together with your request and also make sure to never use the local host endpoint as it won't work inside your code. If you want to explore the API itself, always use the local host one. It might be confusing, it's something we are changing on StepZen side. So for today, please bear with me while doing this. Okay, so what we're doing whereas question number five I guess. Yeah, question number five. So what I like to do is I would say just copy paste the whole block you had here. This part, so const fetch, blah, blah, blah. Just copy paste it and move it over to the articles site. Because what we want to do is for exercise number four, we want to query a specific article. I would place this over 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 I 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. So this is the query to get a single article. What I would do, we just copy and paste it. I will go back to my code and I will put it in here. As I'm using template literals here, I can 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 the destructured influx.

10. Getting a Single Article and Using Named Queries

Short description:

We'll get a single article and go back to my React app. Unfortunately, there isn't a way to get all fields without writing them. Fragments can help with reusing a large set of fields. For a named query, use the GraphQL first and specify a query name. Use the query variables tab to define variables. Replace the hardcoded query with a named query and pass the variables in the body. Check for any errors in the React app.

So we'll get a single article. We'll,.article, and then in here we also but inside the parentheses,.article. We'll save this. I will go back to my React app. Not sure where I left off? At least you stopped hearing me. At least you saw the screen. Any questions about this exercise?

Is there a way to get out of fields without write it? To get the description, the ID, every field that is inside of the article? Yeah. Well, unfortunately there isn't. Okay. I think there is a proposal for the GraphQL spec, the latest spec to have a select all, but currently it isn't because the... The main feature of GraphQL is making sure you select your field dynamically. So that's probably a reason I left it out, but for now, there isn't a way. What you could do is use 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 has 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. 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 put in a name here, so you have the query. It's your operation type, it's this query. You would use it as a keyword, and then you can just type your own query name. So you can, for example, call this get article by ID. This will be a nice query name. And actually, nothing 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 it is also useful for something else because if you look here, we have this parameter hardcoded, which is maybe not the nicest because maybe you have multiple parameters. Maybe you have JSON strings, maybe you have arrays at some points. For this we have the query variables tab right down here. And in here you can actually use JSON to type down your query variables. I will take this part, bring it in here, and use it as JSON 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 because 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 really has changed here, what we have done, though, is we 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 GraphiQL, 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 GraphQL query. And then if we would go to our React app, things should still be working. Okay, error. Let me see why. Bad request. Bad request. Let's see what's going on there. Passing a payload, passing an ID. It's queried 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. We can try. No. So let me quickly see how they do it over here because probably I forgot something, as I usually do. If 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. Then what does this look like? I see... Myself a bit easier. I'm going to put this. See query. I maybe need to append an operation name here And see if that will fix my issue. Running this, set operation name. This and a comma there and then save this again. Go back here, see if this resolves the issue. It looks like it didn't. So what else could I be forgetting? It's probably, ah, it looks like the variables are being. Maybe this doesn't need a string of Pi at all.

11. Using Named Queries and Fixing Filters

Short description:

In exercise number five, we use a named query and pass variables. Named queries are stored in the front-end app for later use. Exercise number six involves fixing a feature on the homepage that isn't working. We use a named query to get articles and apply filters based on the tag parameter. The fetch articles function is updated to use the new query, and the filter prop is passed to the components. The filters now work correctly, and the requests are made through GraphQL.

Could be. I guess that's the reason because I'm already using content application type JSON. Probably don't really have to use a string of Pi. Yes, so it looks like it's already better and then I should not forget to put the body HTML in there, which we found in the previous. So now I'm using a named query, um, which you could see here, so it's using a named query. And we're passing the variables like this, which are bit nicer. Uh, but later on when we start using a GraphQL client, it becomes more important, um, becomes more important. See, Djago giving a nice tip, if you Hover Query in a network tab, you see all it takes without needing to scroll around, it's smart. Um, let me see. So we run this. We can do this. Forget. Well, nevermind. So this was exercise number five. Uh, any questions about using named queries? Just a quick question. Are these queries, uh, stored anywhere for documentation? Just, uh, how can you check the name of the queries that you created or. Um, why you don't really recreate it. We, uh, you don't really create any username at runtime. Um, but later on, if we start using the graphical clients, um, They will be stored in your front end app, and then you will be able to use them later on. Let's see. Okay. Thanks. Cool. And then for exercise number six, you're going to be, uh, fixing an issue we had earlier on, or actually a feature we had earlier on. So if you remember that if it would go to the homepage. We had this nice filter, but currently the filter isn't doing anything, 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. Uh, if it goes to docs, I want you to use the parameter tag. Uh, here from a tag on articles. Do make the filters work. Again, it would go to the goats, to the home. Uh, you can see the value for filter is here, so you need to find a way to pass the filter to the graph query and then use it in the query to get the, uh, articles for this filter instead of all the articles that are available, uh, at the latest time. So per request, we can take 10 minutes for it, uh, to make. The fetch articles function in the whole component also named query. Fast, detect to it. So you can have some filters on the home page. Uh, so whenever you press the filters, uh, the tech will, we'll be updated. So let's go back to the exercises. Uh, we were looking at exercise. Exercise number six. Exercise number six. So do you fetch articles function and source components home? Can we change the user name query? So if we go back to the graphical, um, we can change this one to maybe get articles. Uh, 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. If we run this, probably not much will happen. This probably isn't a tag called one, two, three, four, five, six. Uh, probably is a tag called graph QL. You see this gives some nice, um, some nice results. Probably also use TypeScript here, should give us different results. Actually a article for mine, but it's kind of nice to see. Uh, so what we will be doing, I tested this now in graphical. So this is usually the way you go. If you try it out in graphical, then you bring it to your go. Okay. Just copy, paste this and also make sure to change the name. Because if you have multiple queries for the same name, uh, it seems to be giving issues. So be going to my home components. I'm going to update this thing here to use my new query. Uh, of course I also need to set the variable variables. And for the tag, I will take the filter prop, which I have in my component somewhere, so I have a set filter probably here somewhere. So this gets a filter prop and this time it will be passed to my components. If I save this, I can go back to my application. 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 within XDS. 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 in GraphQL doesn't specify tag property, it has tags and tag list instead. Yeah, could be because the parameter doesn't necessarily have to be a field on its own, I can call this basically anything I want.

12. Using Apollo Client for GraphQL

Short description:

In exercise number eight, we will be using Apollo Client as our GraphQL client. You need to install Apollo Client and GraphQL, create an Apollo Client and a provider in the index.js file, and use the useQuery hook for the home and article components. This exercise requires about 15 minutes and is a bit more advanced. If you finish early, you can move on to exercise number nine. Take the time you need to complete this exercise and refer to the Apollo docs for assistance.

I can also call this input one, or variable one, because this is the function of my GraphQL schema, and the tags I use here doesn't have to be filtered there. The GraphQL schema itself will behave slightly different, I 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 StepZen 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, to make sure that we have sufficient time to 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 exercise, 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, the most used one. You 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 Client. Now, what you need to do for this exercise is install Apollo Client and GraphQL. So this is the GraphQL front-end library that will help you. There's actually a must-have dependency for Apollo Client. So you can install with NPM or Yarn. You will need to add some boilerplate code in the index.js file to create an Apollo Client. And you will create a client and a provider. So it's pretty similar to as you have been using. So as you have been using Redux, maybe in the past, we need to create a provider that will wrap your component tree with the information of the clients. And this is to set up the clients. And then once you have the client set up from everywhere in your component tree, we will be able to use a useQuery hook. And for this, we actually will be going to the Apollo docs. So we can, for example, hit Redux. We have to wait and see if we can get a response in a couple of minutes. Okay. So now we can go to our client and make a useQuery. And one thing we can do by doing a useQuery is to register the client. And, so if we go to this example here of the clinical Firms, is install Apollo Client and 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 a readme as well. And then use a useQuery hook for the home and article components. So we're going to be replacing the fetch request with Apollo useQuery hooks. And the docs are right here. For this, it's a bit more advanced. It's a bit more coding. That's why we really need the 15 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 and gratify. Okay. So this is installed and then I can do NPM start to start my NPM server again. So what are we doing for starters? We'll go back here and I actually copy paste this code and bring it over to my source index CSV file because I need to be creating a provider, very simple. Very similar to how we do this with Redux. Or there are actually more tools that use providers. If you use the React context API, you might also know how this is set up. So adding the imports. Here, I have a client, this would be my compliance infoCollections thing. My API keys, something I can copy here.

13. Using Apollo Client with GraphQL Queries

Short description:

Here, I have a client that needs to be wrapped in an Apollo provider. In the home component, I can use the useQuery hook to fetch data from the GraphQL API. I can also handle loading and errors using the returned parameters. The useQuery function takes a valid GraphQL query and variables as parameters. The data can be accessed from the returned object. The code can be further optimized by restructuring and cleaning up unnecessary parts.

Here, I have a client, this would be my compliance infoCollections thing. My API keys, something I can copy here. So I have my endpoints I have my headers. You can see I don't need to set the content type header this time 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 clients and then what I need to do is I need to wrap my app component actually app is doing all these kind 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 pass the client.

Any questions about this part? No? Nope. OK. 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 a way I'm sure is it in a way to use query. And then so this is my query. Let me just start by doing this. it will work, query, and then it will take some variables, which is this one. And I guess I can delete all this. Let me do this. See, use query, I think there, closing, like this. I'm sorry, it's getting a bit messy, but I will fix it in a bit. Let's zoom out a bit. Maybe just close this. So imports, use query. Maybe do it here.

So, it should be finding... So, actually I also need to delete this part. So, I can actually move all this up top. And I can do this as well. So, actually I can delete this whole use effect function. A little bit clearer what I'm doing here. So, what I will be doing is, I will take this whole use effect 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 Apollo does as far as wall. So we're going to be removing the article state. We're also going to be removing this use effect to reset articles when the filter changes. Instead, you're going to be using this use query hook that we need to import. So, import this query. 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 we need to do it like this because actually we need to restructure this because articles is inside. But it's just the way GraphQL works. And then this would already work. 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 use query hook is a loading parameter, a loading return. We can say if loading return something like this. If I save this, let me go to my... Here, see what it looks like. So it was done correctly all in one so that we need to make some more changes. We probably have to argument a query. Yes, I also need to use the GQL function, which I can get from here, GQL. And I could pause this line here. Format this and go back. I should be getting data here now. But I've known cannot read properties of undefined. To be sure, do it like this. So now you can also quickly see the 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 GraphQL 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 guests.instora.articles. And then I could just take this, Delete aroma, then put this thing in here. Format, and then we should be right again. Let's see if that works. So, this is how you 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 this string into a GraphQL node. And then we pass the variables here which is the second param. And I guess there is more params. Let's see, operation variables. You can also pass any other options. Let me see if the text still works, actually.

14. Using Apollo Client and Introducing Mutations

Short description:

To use Apollo Client, you need to put the variables in the GraphQL query and create a constant for it. Apollo Client sets the state, eliminating the need for manual state updates. If your application grows complex, useEffect can be an alternative to useQuery. It allows you to query the client directly and handle state updates yourself. Exercise number nine focuses on mutations, which allow you to update data using GraphQL. Instead of doing exercise number nine, it is recommended to proceed to exercise number 10. However, you can add the upvotes for each article by modifying the query and destructuring the upvotes field.

No, so what I probably need to do is I need to put like this and call this variables. Let's see how it works. 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 delete this. We can delete all this. We can copy paste the code we had before. This time we're passing a param, which is ID, and this was params. We're gonna be taking this GraphQL query and we're going to create a constant for it again. Const gets particle by ID, like this. I already have my template literals, like the one. And this can also delete new states. This one's a setting state. I need to replace this with this and then of course I also need to import these things. And then in here I need to say data, data.article, this is easier. And now if I will be clicking on an article, it should be getting the article again. So pretty similar, we're again using loading data. We don't use the arrow just yet. If stuff is loading, just return loading, if stuff has finished loading, so this is asynchronous. We'll go from top to bottom, so we can destructure article from this thing here and then get all these variables, see if they exist. And 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 Apollo, we don't need to set it by hand anymore, which is quite nice. Quite some code for free, which is something I usually like. And as Vladislav said, it's a bit annoying that you have destructure it like this. But, I mean, we had to do the same thing previously already when we destructure the result 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 get used to. In the end, it's only one time destructuring, while with REST, you're maybe doing infinite amounts of destructuring. But yeah, that's using Apollo Client. Any thoughts about using Apollo Client? Do you like it? Do you dislike it? If you didn't have the time to form an opinion on it, that's also fine. I mean, it's maybe your first time interacting with it. And yeah, 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. I should probably also mention that if your application grows, if your front-end project might be a bit confusing at some point, or it's hard to tie all the data together, usequery might not be your best option. 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 an useEffect, like this, useEffect. What you can do in here is you can still get a data variable. So what you can also do is constant data is client.query. For this, we need to import the client from here. So we need to export it. And then in 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. You need to make sure you do the upstated dates 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 may be the 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 you as a developer, of course. I usually like to tell people how to use this query. You already know how to do 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 you might be able to finish in time, which is nice. For exercise number nine, we're going to be looking at mutations. So we already learned that we can use GraphQL to query data. So what we will be learning now is how to use GraphQL to mutate data, meaning that you can update data instead of just reading it. And for this, we will be using mutations. 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 upvotes for every article to the screen. So our query here also has a value for upvotes that we also want to use here. So maybe we can do it in a similar fashion as we have here. Left. What is the label style? Maybe we can do upvotes. So please code along. So inside home.js you have your query for getting articles. And here you need to add a new field called upvotes. And then going down, whenever you destructure the articles, you need to destructure upvotes there as well.

15. Upvoting Articles and Using UseMutation Hook

Short description:

To upvote an article, use the mutation called upvoteArticle. Set the post ID and the mutation will return the upvoted article. The upvotes are stored in a Firebase database. Try out the upvote article mutation in GraphiQL to see if it works. You can also use query variables to specify the post ID. For exercise number 10, use the UseMutation hook from Apollo to add an upvote button to the Home component. Rename the returns of the UseMutation hook and handle loading, error, and data. This will allow you to upvote articles by clicking the button.

And then you can just put it in a span to display it. And if I keep doing this, I will be seeing upvotes here. These are my upvotes. You can see there is zero everywhere, because we haven't upvoted any of these articles yet.

So if we would go to our exercise number 10, we can add a button to upvote an article, for example, by using the mutation called upvoteArticle. So we would go to the Graphical. We can use this to get articles. Just get all articles, don't really need the tag anymore. And we want to get the articles, we want to get the ID and the number of upvotes. Verify this for me. So everything has an upvote called upvotes with a value 0.

We want to stab, 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. You can type mutation here, we can type up vote article. We need to set the post ID. And I'll just do it manually now, it doesn't really matter. So article here. I like this, so this my mutation to upvote an article, and then the graphical will ask us which thing we want to use, the article. And as you can see, it gives me a return. So now we're in getarticles again. You can see the upvotes are there. And either this is duplicating or someone else is trying it as well. So we're assuming someone else is trying it as well. The same here, can upvote a different article. And then get the list of articles again. And I see the upvoted one there. So this is all being stored in a Firebase database. I told you before, I use Steps and 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. But for you it doesn't really matter because I already created this API for you. Let me retrieve this again. So yeah, please go to your GraphiQL and try this out. Try out this upvote article, see if it works for you. And then you also get a feeling with notations and see that they are very much the same as using queries. You can use the name setup 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's still work as expected.

So, yeah, any upvote anyone in this group is doing will also show up here. So if you see strange numbers, maybe something increases a 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 read. Please go away with this zoom handlebar. So exercise number 10. We want to be using a Usementation hook from Apollo to do this. And Usementation hook is quite similar to the hook we saw before, which was the UseQuery hook. Let me put this link in the chat as well. It's quite similar. So we have a Usementation hook here and we can use it whenever we click a button. 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 Usementation hook here. So that's Usementation here. As it also returns data, so you might need to rename the returns. Abuse mutation. Something else, so probably we need to do const. Loading error data use mutation, maybe something like this. Delete this, it's confusing. Probably need to be renaming these loading mutation. Error mutation. Data. You probably need to be renaming those similar like this because we're gonna be using two hooks in here. And then in here you would like to set a button to probably upload, so maybe. Add the upvote button there. So there's a couple of things you need to do, you need to add a notation, you need to get a response, you maybe need to add an upvote, you also need to add an upvote button. And this will upvote the articles whenever you click it by using whatever the notation returns. Let me see if the upvotes are working here just to be sure that we're not going crazy. Photo article shows there, articles shows there.

16. Using Apollo Client and Updating Upvote Count

Short description:

We need to get a use notation function from Apollo Clients. The use notation function returns an array with an update function. We write a use notation that takes a query and a variable. We also need to create our notation. The button is used to upvote an article. There was an issue with the post ID not being a string, but it has been resolved. Any questions about this exercise? The next exercise is about seeing upvotes without refreshing the page. Exercise number 11 involves writing a query that updates the upvote count every time an article is upvoted. We will be using the refresh queries option. Let's do this exercise together and then have time for Q&A and round up.

Okay, so API wise it should work. Let me go to the code, see why it might not work. So for starters, we need to get a use notation function here. First import it from Apollo Clients, use notation, and then the return of the use notation is slightly different from what we saw before. So it actually returns an array with an update functions. So this is update function. You can call it whatever you want because it's an array. Then the second part is the objects we saw before. Then we write a use notation. We'll also takes a query and also actually only take this variable here. Of course, we need to create our notation here as well. I'm going to be going back to graphical, going to be taking this one here. What I can do is say const the photo article, this thingy, and then close with the template literal. One, I use this thingy in there, it looks something like this. During my App Students break right now. Then if I have this update function here. Let me create this button. Set it to the button. Let's make it to title. Let's load and say, onClick to do some stuff onClick. 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. I see a tiny little button. Now, I'm seeing an upvote button. Let me see if we can find Vladislav's issue. At the network tab. I'm going to be clicking, let me just scroll down, Music Monday. Upvote. Operation. We have a post ID. I think I see the issue there. Refreshing this. We don't see it updated. I guess it is because, and it's weird because we should see an error for this. This is supposed to be a string. But somehow this still works, so that is super, super weird. Maybe we should do it this. Huh, that is weird, sorry for that. What we need to do is we need to make sure this is actually a string. How do we do this? I will do it again. This probably is done. This should be working better. Let's pass it as a string. And if I refresh the page, it is showing a flood one. This flow is supported. 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... Well, something to figure out later. So 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 upvotes 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, we could do this exercise 11 together and then we would have some time for Q&A and round up. That's okay with everyone? That's cool. Okay. Good. And that's fine. So let's do that. So exercise number 11 is every time you upvote an article account you'll be updated, you write a query. So every time you upvote an article account you will be updated. For this, we're going to be using the refresh queries option. This is an option. Using all these. We could actually use this loading button here as well by the way. What we will do is. And maybe say. And maybe say okay, so what we're going to be doing for this exercise is whenever you want to press any of these buttons, and it's not working perfectly because what I actually wanted to do is change this into a separate component.

17. Automatic Data Refresh and GraphQL Code Generator

Short description:

To automatically get new data whenever you change something, use the Refetch Queries option. There are two ways to do it: defining an object with the query or referencing the name of the query. This was the final question for the introduction part. To learn more about the course, drop your email address in the form provided. GraphQL Code Generator is a helpful library for generating TypeScript types based on your GraphQL schema. It eliminates the need to type all the functions and variables every time you make a change.

So now it's loading everywhere, it's a bit annoying but it can easily be fixed by refactoring how the components are structured. But I wanted to skip this part today to make it not too overwhelming.

For this mutation here we'll take an object here which you can do a refresh queries. And in these 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 we've saved it. And we do this. We're going to refresh the page. It's a refresh and you can see the value updates. There is a minor lag in it. Let's quickly, react. So maybe the test API I'm using is getting a bit overwhelmed. Or requests. Maybe we're just doing too many requests. So support to the minor lag. And you can see it going up now every time we press. That's by using the Refetch Queries option.

There are two ways to do it. You could do it this, by defining an object with 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. To 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 new data whenever you change something. And I guess this was the final question we had for the introduction part.

Usually I 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, to drop your email address in case you want to learn more about the course later on. Here's the link again in case you want to be updated. Something else I wanted to show you is called GraphQL Code Generator. This is part of the full day workshop actually that I do. This is a cool library that helps you to generate TypeScript types based on your GraphQL schema. If you would have GraphQL schema and a set of operations which are the queries that we have in our app and a plugin in which you define what you want to generate. You can generate all these GraphQL types based in your schema automatically on build type. It is cool because if you're using TypeScript in your product, good way you don't have to type all the functions and variables every time you make a change. This final thing I wanted to add to today's workshop. Thank you. 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.
React Summit 2023React Summit 2023
151 min
Designing Effective Tests With React Testing Library
Featured Workshop
React Testing Library is a great framework for React component tests because there are a lot of questions it answers for you, so you don’t need to worry about those questions. But that doesn’t mean testing is easy. There are still a lot of questions you have to figure out for yourself: How many component tests should you write vs end-to-end tests or lower-level unit tests? How can you test a certain line of code that is tricky to test? And what in the world are you supposed to do about that persistent act() warning?
In this three-hour workshop we’ll introduce React Testing Library along with a mental model for how to think about designing your component tests. This mental model will help you see how to test each bit of logic, whether or not to mock dependencies, and will help improve the design of your components. You’ll walk away with the tools, techniques, and principles you need to implement low-cost, high-value component tests.
Table of contents- The different kinds of React application tests, and where component tests fit in- A mental model for thinking about the inputs and outputs of the components you test- Options for selecting DOM elements to verify and interact with them- The value of mocks and why they shouldn’t be avoided- The challenges with asynchrony in RTL tests and how to handle them
Prerequisites- Familiarity with building applications with React- Basic experience writing automated tests with Jest or another unit testing framework- You do not need any experience with React Testing Library- Machine setup: Node LTS, Yarn

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!