Fetch, useEffect, React Query, SWR, what else?

Rate this content

In this workshop, first, we’ll go over the different ways you can consume APIs in React. Then, we’ll test each one by fetching content from a headless CMS (with both REST and GraphQL) and checking in detail how they work.

While there is no advanced React knowledge required, this is going to be a hands-on session, so you’ll need to clone a preconfigured GitHub repository and utilize your preferred React programming editor, like VS Code.

You will learn:

- What diverse data fetching options there are in React

- What are advantages and disadvantages of each

- What are the typical use cases and when each strategy is more beneficial than others

102 min
12 Oct, 2023


Sign in or register to post your comment.

AI Generated Video Summary

This workshop covers data fetching strategies in JavaScript, focusing on Fetch API, Axios, SWR, and React Query. It provides examples and guidance on implementing these strategies in a React application. Troubleshooting and deployment issues, such as CORS, are also addressed. The workshop concludes by highlighting the advantages and use cases of SWR and React Query, and encourages participants to choose the best strategy based on their project's needs.

1. Introduction to Data Fetching Strategies

Short description:

Hello everyone! Let's get started with the basics and introductions. Feel free to ask questions in the chat window. Today's workshop is about data fetching strategies in JavaScript. We'll cover FetchAPI, advanced features, processing data, revalidation, and paging. It's an intro-level workshop with lots of examples. You'll receive all the slides and codes. If you need assistance or more time for exercises, let me know. Now, let's take a look at the application showcase, a table of flights on an airport.

So, hello, everyone. I think it's a good time to start now. It's one minute after the time, a few more minutes to join, but we can already start with the basics and introductions. We're here in a Zoom call. If there is anything, you know, you need to ask or if you need more time for anything, then feel free to use the chat window. I actually managed to have it up and running on my next screen, so I'll see hopefully all your messages.

So, feel to say hi. Tell me where you're coming from. I hope it is much nicer weather than it is here in Brno, Czech Republic for me. It is a bit dark already, but it is actually a great time to do a workshop and spend time online, you know? Overall, I hope you can all see my screen. It is currently showing power point presentation. If you can just let me know if you see that because that is probably the biggest prerequisite to this workshop. Yes. Hello to India. That's nice. Coming from France, perfect. Same other way. Christof, I'm filling for you. It is October. What can we do? If you're coming to London next week, it will about to start. And there's a lot of people there. That is great. So, yeah, there we go. And we have a Prague here as well. Nice. It is great to meet you, all of you guys. I hope you're going to have fun. You're going to learn something new today. And the biggest achievement I will do today is just to have fun. To learn something new and see what we can do in the allocated time. Now, I aim to make the workshop under two hours so that we don't lose concentration. It's for most of us, it's after work time right now. So let's get to it. And let's see what we can do.

So, first of all, I'm Andrey. I'm a developer evangelist for Content.AI. We're a headless CMS spender. But today's workshop is not going to be about headless CMS at all. So this is just one slide to let you know where I'm coming from. Overall, we're going to be talking about data fetching strategies. And the agenda for today will be the following. So, first of all, I want to show you or I want to talk to you about the actual data fetching options that we have in JavaScript. That will be about FetchAPI. Then we're going to talk about advanced features in data fetching. that means how do we handle errors, how can we intercept requests. How can you implement or configure the retry policy? And then we're going to talk about processing the data on the application side. So, right now we call it data fetching. But libraries that actually let us do all that, they also have caching mechanism and other features in place that make it easier for us. So, we're going to look at some advanced use cases as well. We're going to look at the revalidation cases, that means when you have data in cache, you need to revalidate it either automatically or manually, or you want to prevent it actually, that's also one of the use cases. And the last one will be paging, which is almost on every project that needs to work with some lists of data. That's about it. I think that's a pretty packed agenda for today. Now, just to to give you guys an idea, this is going to be at the intro level. If you're an expert on React, maybe this will be a bit boring for you, but there will be a lot of examples, a lot of show cases, so you can test it on your own. If you have Visual Studio prepared, that's a good start. Just so you know, I won't go into the large or great details of React query or of USEr's VR and so on, because we could be here all day. Yeah, so, just to give you an idea of how this is going to work, now, of course, this is recorded, so if you need to get back to any point of the webinar or workshop, you can do that later, and I'll also share the presentation. Yeah, so, you'll get all the slides. You'll get all the codes. No worries at all. And if there is anything that I can do for you, if you need me to answer anything or if you need more time to do the exercises, then let me know in the chat window. I did the examples so that you can follow along. So, I'll give you the codes and I will give you time to work on the examples. It's very easy, nothing to be worried about. It's pretty much just so that you get your hands on the actual code, so that you don't just look at what I'm doing but you also try it out on your own. So that's about the agenda and first of all, what I wanted to show you is the application showcase, the application that we'll be working with because obviously for everything we do in the workshop we need to have some kind of a front-end. So, this is what I actually created. It's just a nice picture of a Swiss aircraft landing in Zurich but it's just to make the website look nice. This is a little bit off but that's because I think there is a HTML tag mix up somewhere but this is just a table of flights that could be on an airport.

2. Introduction to Data Fetching

Short description:

It's about the data and the network request that we'll be making. We'll focus on the frontend part. The backend part is there just to support us. The data are coming from a Headless CMS. The functions are already deployed on Netlify. You can run it locally if you want. The first part is about the functions and index TSX.

It contains flight numbers origins destinations and so on. It doesn't really matter what the table shows. It's about the data and the network request that we'll be making.

Just so you know, all the data they are stored in a headless CMS. Content, as I said, I work for them but we're not going to work with the CMS at all. I prepared Netlify functions that will actually give us the data from API handlers so just so you know it's going to be giving us data about flights and this table is something we want to accomplish to have it listed here. There will be more things like next and previous page and so on. We'll get to that but just so you know this is the front end and we'll see how we can get it to work. So that's the most important thing now.

Another thing and that will be the first task for you guys. There is GitHub repository with the URL that is right now on the screen. I'm going to send you the link to it to the chat window so you don't have to write it down from the powerpoint presentation. So if you want to go there, there are two branches. One is workshop start, one is workshop results. So obviously you want to start with the workshop start. The readme is just a sample from creating the React app so not really relevant for this workshop. But what I want you to do is just clone the whole repository somewhere where you can run code. Somewhere we can open with Visual Studio Code. It contains all the files that we will need. So I'll give you a few minutes to actually do that. The start is not going to work. It's also not going to compile. So don't be surprised because it has some code missing. But we'll work on that. So I'll give you a few minutes to do that. The link is there so we should be good to go in a few moments. Let's go through the repo so you're up to speed with everything.

So there are two parts of what we'll be doing today. We'll focus a lot on the frontend part. So the backend part is there just to support us. And to understand how it works is there is a folder called functions which has four functions implemented. What they do, oh, by the way, while you're at it you might as well run npm i to install all the packages. I already have them here so I don't have to do it, but you might want to install the node modules while we talk about the repository. So, as I mentioned the data are coming from a Headless CMS. Now the Headless CMS has a project somewhere, it has environment id somewhere. It gives us data about the flights. Now, we don't have to run this. If you have Netlify CLI running locally, I can give you an environment id which you're going to have to pass into your environment file if you want to run the functions locally. That's also possible, but you don't have to do it. The functions are already deployed on Netlify. Let me give you the address of that. And that's actually here. So this is the URL of all the functions. They are already deployed there. So we should be able to get similar results as I'm getting. This is actually getting all the flies. This would be another function that will sometimes give me results, sometimes give me 500. So seems to be working well, so again you can run it locally if you want. I can give you the environment ID. If you don't want to run locally then this will be the address that you will use in the fetch calls. So that's the first part, those are the functions. They are configured to be accessible via slash API slash name of the function. You see there are a couple of them. They all do the same thing but the first one actually gives you all the flights. The slow one will actually give you all the flights after five seconds. So this is just a simulator we can retry or simulate timeouts. There is one that's called unreliable which will give you the results only once in five tries. So based on a random number. And there is one that apart from the will give you the total number of flights that are available. So we can do paging later. So these are all the functions. It's all pretty the same. And again, you don't have to run it locally. I'll give you the URL so you can run it. We can all work with it from the remote endpoint. And so this is the first part. These are the functions. Then, of course, there is index TSX. It's a simple React sample, so it has only the app inside.

3. React Sample and Data Fetching Strategies

Short description:

It's a simple React sample with the main application file, scripts, models, and components. We'll be editing the code and adding components to the main application. The functions are already implemented and getting data from the CMS. The workshop focuses on data fetching strategies in JavaScript applications, covering the actual request and data retrieval. There's a Q&A section where a question about a URL error is addressed.

It's a simple React sample, so it has only the app inside. It also has a query client provider. I'm going to get to that later. We don't need it right now, but we'll need it later for React Query. But just so you know, this is the entry point of the application.

Then there is an app TSX file, which is the main application. It contains the image in the background. It contains the basics of the table. And it has this is the place where we're going to add our components later. So this is the main application.

And there are a bunch of scripts. We don't have to care about scripts. There are a bunch of models. Again, we don't have to care about those, because that's a headless CMS part. So we don't need to work with that right now. And there are components. Components is going to be the most important part of today's workshop. So I'm going to go through all of those in greater detail, just so you know, this is the code that we're going to be editing. And these are the components that we're going to be adding here just before the end of the closing tag of the table. Yeah. So this is the place where we're going to always add one and see if it works on the front-end. So there's the design of the workshop. Hopefully we're all here. So that would be almost all from the project side, I think, or I can give you the environment ID as well. So if you want to run the functions locally, this is the only thing you need in your environment file. Yeah. Nothing else is needed. API key is not needed. It's only for generating the models, but the models are already there. Marco is checking will there be a recording. Yes, there will be a recording. So if you're missing anything, no worries, you can always go back. Or you can send me a message. I'll explain. Happily. So that's the basics of the solution. Now, this is again the URL address where the functions are implemented. They're already working, so they're getting the data from the CMS, and I already sent this in the chat window, so you should be able to just copy-paste it. Right. And that brings me to the first part of the workshop.

So, the workshop has a title Data Fetching Strategies. Now, there are two different meanings of data fetching in the Scobo JavaScript applications. And the first one is the actual, like, this is what we always imagine, right, when we talk about data fetching, it's always the React application creating a request to API, API returning back data. But in reality, it looks a bit more like this. So, the React app usually has a lot of features, usually has a layout, usually has some kind of a store that you use to store data and to store the state on the client side, right? When you want to work with components. And each component needs to have a different data, but you only fetch it once and so on. So, the store is typically there. And you see that the store is communicating with features. Some features are actually getting the data into the store. Sometimes the store is getting the data from the API on its own. So, it's pretty complicated. Even for simple applications, it's typically pretty complicated. And you see some components even get the data outside of the store. So, in this case it's the layout that requests the data from API. Of course there can be multiple APIs that typically there is. So, in the scope of this workshop, I want to divide this into two groups. The first group is about the actual request and data. So, when we have a component, we have a store, we have a feature. We don't care. It's about only getting the data from the endpoint and getting back the JSON or the data that we want. This is the first part. And for that first part, this is of course the same thing, yeah, when the layout communicates with the API directly.

So, there's a question. Did you mean, as the mentioned URL, this is showing page not found error? Is it really? It should be that URL. I think you have an extra slash there. If you go to APIs.Flights, it's going to be data. So, can you try this? Hopefully, it'll work for you. It should. Perfect. Okay.

4. Data Fetching Strategies and Fetch API

Short description:

We'll discuss the basic requests, state, and advanced features like paging. We have three options for data fetching: XMLHttpRequest, Axios, and Fetch API. Fetch API is recommended as it's easy to use and available in most browsers. A polyfill can be used for Internet Explorer. Fetch API is supported by current browsers, mobile browsers, and Node.js. For a task, we'll add a Fetch call to the Fetch TSX component and resolve the JSON response. Then, we'll import the component into the apt-tsx file. Some files may need to be renamed if they can't be compiled.

So, first of all, we're going to be talking about this, the basic requests. Then we're going to talk about the state and about the advanced features like paging and other things that I talked about earlier.

So, when we're fetching data, it doesn't matter, it can be React, it can be Angular, anything you want, we typically have three options how we can get data from a remote endpoint. First, the old one is XMLHttpRequest. Nobody uses that these days, I think, in its raw form because we have Axios and we have Fetch API.

Now, Axios and Fetch API are slightly different, but they all do the same thing, they just want to make the data fetching easier and better for developers. Now, Axios... when we're talking about the raw requests and responses, we have two options, pretty much the Axios and Fetch API. The difference is that Fetch API, you see, it's really easy to use. This is the only thing that you need to do. The biggest disadvantage, or you could call it the disadvantage, is that it's not available in all browsers, but otherwise it's a native API, so you don't have to install any package, you don't have to do anything. It's all... it's already available in all the browsers.

So Fetch API is something that you should be using by default, and even though it's not available in all browsers, and by all browsers, I mean Internet Explorer version 11. If you need to, you know, work on projects that have to support this browser, I'm sorry for you, but there is a polyfill that you can use to actually bring the Fetch functionality into those browsers as well, yeah? So this is also a solution if you want to use Fetch. Now, this is a screenshot from Can I use? You see that it's pretty much all green, only the Internet Explorer here, but otherwise, all the current browsers and mobile browsers, and also Node.js, they support Fetch API by default, and you don't have to install anything. In Node.js, the support came early last year. So you have to use Node.js at least 17.5, but that should be always the case these days. And as I mentioned, there is no need for extra plugins. Now, of course, you're typically able to handle 85-90 percent of all the cases with just Fetch API. There might be some cases where we're going to need a bit more than that. But that brings me to a first task that I have for you. And that is to actually start working on the application and see it up and running. So the first task is to add the following Fetch call to the component slash Fetch TSX. I'm going to show you how to do that. So when we open the Visual Studio, there is a component under source and components called Fetch TSX. And you see that it's showing some errors because there is a Fetch call missing. So we're just going to use that. We're going to add that here. Make sure to keep the S responses, blah blah blah there because it's still using the typed data from the CMS. And we're going to do here await Fetch. And here you see that we only need to provide the endpoint URL, yeah? In this case, if you're using the remote endpoint, it's going to be the URL on Netlify. And of course we're going to have to resolve the JSON here. So, something like that should work. So first of all, we're awaiting fetch, just the fetch. It doesn't need any import, anything. It's just the fetch. We're fetching the URL. And then we're doing another await for JSON. So we need to convert the string into an object. So that's why we're doing JSON here. Of course, we could do with, we don't have to use async await. We could do with promises to do a dot then and so on. I just prefer this notation as it seems a bit more clear. But that will be the first task for you to do this. And when it's actually saved, you can go back into the apt-tsx. And as I mentioned before, just before the closing tag of table, put the component there. And of course, there is no import, so it's going to want that import from us. Yeah, add import from components and fetch. And save that. Now, I was always using the defy def, but I think that NPM run-def should work too. Or not. Okay, maybe NPM run start. Let me check. Okay, let me check. Yeah, NPM run start should work. Okay, and the first, the first problems, yeah, there are components that it doesn't like because it cannot compile them, so we might need to comment them. XCLS, XCLS, React query. React query. So, if you're using this, if you're using NPM run start, we're probably not gonna have to change that. If you have netlify-cli installed, if you run netlify-def, I think it works, even though there are problems, but let me check. Otherwise, we're just gonna have to rename the files so it doesn't pick them up as TypeScript files. Yeah, he doesn't like them too. Okay, sorry for that. We're, that's one more step that we have to do. So, the files that are not able to be compiled, we're just gonna have to rename them. NPM run start. Are these up? Oh, this will tell me which they are. Oh, okay, now it works.

5. Troubleshooting and Deployment

Short description:

Now it works. Axios was the problem. Cross-origin issue. Run it locally with Netlify dev and change the call to slash API slash get flights. Comment out React query and SWR. Create an environment file. Check if it works with CORS using Netlify CLI. Access control allow origin error. Working on getting Netlify functions compatible with CORS. Deploying to resolve the issue. Anyone depending on remote endpoint or running locally?

Oh, okay, now it works. So maybe just Axios was a problem. Now it seems to work. Of course is not getting any data. So let me check what's wrong there. Oh, cross-origin, okay. That's a bit of a problem. Okay, in that case, if you can actually run it locally, that'd be easier because that will remove the need for hoarse in this case. So if you can run it locally, then I think you can just run Netlify dev and change the call to slash API slash get flights. And that should give you results locally. Let me just quickly check that.

Then, no. Estimating unexpectedly, okay. Let me try this again. Okay, now we got problems with another component, React query and SWR. So we need to comment those out as well. Yeah. I will see if it works locally. When it works locally, we're just going to try and fix the error on the remote. Now, there's still some problems. Let me try it again. Okay. Okay, now this works. Okay, so if you can run it locally, then that's the easiest. So just create an environment file with this. I'm just going to paste it in the chat. Yeah, you can also do it in a tsconfig, but we're going to have to use those files later anyway. So I think this will work. So locally, this should work. If you do this with the environments file, this should work. With Netlify dev, if you can do it locally, then let me check if we can actually run it with CORS. So we should be able to do that here. Okay, I'm gonna have to quickly check. So I don't remember that from the top of my head. Yeah, I think you need to do that. Yeah, Netlify CLI. It's like NPMI. I think it's netlify and "-g". Something like that. That should work. And let me check quickly. What's the fetch course notation. So I don't remember that from the top of my head, but we should be able to find that quite quickly. Here it is. And let's see if that's gonna actually help. There was a mode course. Just a second. And we'll see if netlify functions actually allow that. I think they should. We'll see in a second. No, it doesn't like that. Access control allow origin. Okay. Okay. So I'm going to have to do one more step here. And let me just do it elsewhere. So I have to go to netlify to see. So installing and running a defy with fetch returns the data from it. Perfect. Thank you very much for confirmation. I'm just right now working on actually getting the Netlify functions compatible with course. I think that this should do the trick, but I actually have to push that. So if you've been running, then give me a second. I'm just going to try and resolve that for everyone. Okay, so it is deploying now. It should be working in a second. So is anybody depending on the remote endpoint or do you guys have it running locally? Let me know if someone wants to run it remotely. Yes. Okay, perfect, no problem. It should be there in a second.

6. Deploying and CORS Issues

Short description:

Deployed and encountered CORS issues. Tried different configurations but still not working. Finally found a solution by returning headers with status code and data. Now the function is working properly.

Okay, deployed now. So we should be good to go. Let's see. So we've got more course. Let's close this and let's check. Okay, I probably have to, oh it is running. Port 3000. Okay, still not working. Let's see. Okay, that should work for the course config. Yeah, the course config on a fetch is quite easy, just provide it here, but right now we have to enable it on the Netlify side as well. And for some reason it's not returning the course. These are the right headers. Let me check that in Postman in a second, for a second.

Yeah, it's not doing that. If there's anybody with the Netlify functions extensive knowledge, then let me know if we're actually doing it right. So I did this, but it doesn't seem to work for the functions. Oh, I think we also need to do this for the redirects. Maybe that's the problem. Redirecting from the original destination. So let me try that again. And hopefully that will solve everything for us. Now, I'm triggering another deploy. So hopefully this will work now. Let me restart this. And it seems to be published, so hopefully this will work. Let's see. No. It's showing me course problems. Okay, is there still someone... QueenKey, I see your message. Is there someone else who needs to have the remote endpoint? I can't seem to get it up and running like this. And I don't know why because it should work. One last try, I'm gonna try the API. Instead of the API, I'm gonna try the full URL. But otherwise, that's this part. Yeah, I'm gonna just try this URL. Let's see if that will help. Yeah, it's still showing me course problems. And I don't know why, honestly, because in here we have all the headers done. If there is someone who sees what I'm doing wrong, let me know. Maybe there is something that I'm not seeing here. But as far as I see, this should work. And look, it's actually working. So the function is not really like, yeah, let's see. Yeah, this is what I tried, actually. This is what I tried. That's exactly what I have in there. But for some reason, it's not working. See, that's exactly this part. It's always the problems with CORS. Anyway, I think we're just gonna move on. Shouldn't you use localhost URL in React? At the bottom it says they did an options check in the function itself. Okay, let me see. So what they did is they returned the headers with the status code and data. Okay, that's something that I would really want to avoid. So they did it here, okay. Okay, we can try to do it. One last try, then we're gonna move on. So let me check that. And let's save that. I'm gonna try it on one endpoint and we'll see if it works for the others too. Okay, it's building now. We should see in a second. And okay, it finds. Of course, now we can go back to the API. Okay, now it's live. Let's see. Okay, here we go. That worked.

7. Using Axios for Data Fetching

Short description:

Axios is a basic way to get data from a remote endpoint, providing more options for request and response interception. It offers features like response timeout, retry policy, and automatic JSON data transformation. In the component Axios.TSX, we use Axios.get to retrieve all flights from the specified URL. We also update the import and change the fetch to Axios in the App TSX file. However, we encounter a 404 error, which is due to a missing letter in the URL.

So can you guys, or Pingy, can you please verify that it works for you now? It's the get flights endpoint. Yes, it's glorious. Perfect, okay. Live debugging, always fun. Perfect, so now that we have the fetch up and running, we can hopefully move on. So let me just close this. Close that as well, and close this one. So we got the fetch here. And at TSX we have the fetch here as well. Now, let me see, what can we do next?

Next is Axios. Right, so this is the most basic way to get data from a remote endpoint. Of course, with Axios you get a bit more options. Oh, just close this. You get a bit more options, mainly in terms of request and response interception. So sometimes it happens that when you're building the URLs, you're building the options object, you're combining modes, you're combining data and so on, and something doesn't work, then Axios actually gives you nice options for request and response interception. We'll look at that in a second. It gives you options for response timeout. Now, of course, this is also possible with Fetch API, but much more complicated way. So when Axios, you only define what's the timeout, and it's gonna be canceled by that time. It also allows you to apply a retry policy. So when a request comes back with a problem or gets lost or something, then Axios will let you retry it and has a support for older browsers. That's why when you're working with SUS services and they give you their SDKs or anything like that, you typically see them use Axios because it provides the best compatibility for the older browsers, because Axios is based internally on XML HTTP requests. That's a bit of sherry on top, but it allows you to... It gives you automatic JSON data transformation. So we don't have to do the await.json, but it does that automatically. That brings me to another task and that's the same thing as we did until now. That's a component Axios TSX. This is just the single line that gets all the flights. So let's go there. Now rename that back to Axios.TSX and add the call here. So what we actually wanna do is await Axios.get and use the same URL. So either api slash api slash getFlights or the Netlify URL. I don't have it in Clipboard anymore. So I'm just gonna copy paste it from here. So OOTB means Out-of-the-box. Sorry for that. So out of the box. So that means you don't have to solve it anyway. Like with fetch API, you had to do it with the polyfills. With Axios you get that by default. So let's see Axios.get And we have to do the brackets once more because we're getting the whole object. We only want the data and we're setting the flights. So let's save that. And don't forget to go back to App TSX and change the fetch for Axios. And make sure that the import is components-Axios. So probably is gonna want some imports in the files as well. I already have them there. But if it needs some imports, then just make sure that you have them. And that actually compiles, but it should work. Now, let's see, no issues found. I like to see that. And let's see, oh yeah. It's not working. Again, of course, I think if you're working remotely. So we need to add the course mode here as well. So we're probably gonna need the mode here as well. Of course. Oh, let me check. Google always knows the answer. So these are pretty much the biggest differences between Axios and Fetch, that the syntax or the configuration is a little bit different. So you kind of need to know what you're working with, but otherwise, they provide pretty much the same functionalities. Although Axios has a bit more features, it's a bit nicer to work with, but requires an additional package. Let's see. Interesting. Why is it not working for me then? Axios error. Oh, 404. That's a different thing. Get flights. I'm missing actually one letter. Let's see.

8. Intercepting Requests with Axios Interceptors

Short description:

Let's move on to intercepting requests using Axios interceptors. By adding an interceptor, we can log all requests made by Axios to a specific URL. This is useful for debugging and working with cache. The code provided shows how to intercept requests and log them to the console. It also includes an optional error handler. After implementing the code, you can see the logged requests in the console when accessing the page. Remember to add a unique key prop to resolve any warnings. Now, let's proceed to the next task.

Nice. Okay. Interesting. But the good thing is it's not working. So that's good. That's the Axios part. But let's get into something a bit more interesting. So if it's working for everybody. If it's not working, then let me know. If it's working for everybody, then let's go for the next task, which is intercepting requests. This code actually makes Axios add an interceptor before it services the request. And what it does is it actually checks all the requests and logs into console that the request was sent by Axios to a specific URL. So. This will actually intercept all the requests. It will also allow us to see when each request was fired into network. When we get into SVR, when like right now we're only doing requests, then we're also gonna work with cache. So this is a beneficial for that case as well.

So here we're just using the interceptors and using a configuration that provides us the URL. And in case of an error, we're just gonna reject that promise and return the error. So this is the component Axios intercept. And I'm just gonna try to do the same. So, I'll do that there. So you want to see Lucy, You want to see the Axios.tsx? Sure. Which part do you want to see? Is this okay? Hold it for one minute. Sure. No problem. So the other component is right beneath it. It's axios intercept.tsx. I'm gonna switch there in 20 seconds. Perfect. Okay. Perfect. Okay. Now we can go here, so there is already the comment at the intercepted form here. So that's what we're gonna do. So axios interceptors. We wanna intercept the request. I think the use and config And we can just return the config, yeah. So this is what we're actually doing. Like we're getting the requests and we're returning the request if we don't wanna change anything. If there's something that we wanna do, just like we want to do the console.log. We can do that. And you see that with the config, you get all the details of the request. You got the headers. I think somewhere you also get the data and there's the URL. So we wanna get the URL and return the config. And of course this, the next part is optional. Like if you want to do the error, this is the error handler. So it's here for the case when you wanna intercept the error as well. In this case, we're only returning the reject of the promise. And we can provide the reason. And that's it really. If you save that and again, switch the components in the app TSX, you should be able to see this message every time you refer to the page because there is only one request per page right now. So let me do that, Axios intercept, and it's gonna add the import automatically. Now when I go back to the URL, okay, I'm getting errors. API and let me just fix that. Okay, now we get the data here and in console, you also see requests and the URLs slash API slash gets files. I think this is previous. Here we have the full URL. So you see to which URL the request was sent. So you see once per page. Of course there's the warning, each child analyst should have a unique key prop. I did not really focus on the front-end, but if you want, you can just add the key here, system ID for example, and it's gonna get rid of that error. So give me like a half a minute. Then we're gonna move on to the next task. Back to coach, sure, no problem. So this is the code. It's actually under xus.interceptors.request, and it's using the config. Again, this is just an object that you're able to change on its way to the remote server. All the rights.

9. Retry Policy with AxiosRetry

Short description:

I encountered a problem with the key, but it doesn't affect the data retrieval. Let's move on to the next task, which is the retry policy using AxiosRetry. This library allows us to define the number of retries and the delay between each retry. It's already installed in the project, so you can use it directly. Just provide the Axios instance and the config with the desired number of retries and retry delay. I'll fix the endpoint so you can try it out.

I hope that we're finished. I got four locks for some reason. So if you're getting the problem with the key, I just fixed that. That was this part, but it's not something that you should be worried about right now. We're focusing on doing the interceptor not on fine tuning the front end. It's a good practice to have the key there so that you don't have to re-render the whole thing every time. But it's not something that would prevent the data from coming in.

There's a comment on the right. Oh yeah. No, we get it three times. That's interesting. Let's see. There must be something with the React performance. Yeah. But right here, I'm not sure actually why we got three of them. Yeah. Yeah. Let's add that there. Let's do it. Are we still doing that three times? I don't know. Don't know why. But it shouldn't do the request three times. It should do it only once. Anyway, maybe we'll figure it out later. Yeah, we're in a strict mode. Anyway, let's move on to another task. Let's see if that gets any better later.

The next thing that is prepared for us is the retry policy. Now, there is a component called AxiosRetry. This is not the best way to handle retries, and we're gonna look at SVR later because it's much easier to implement. But with Axios, there is actually a library, it's already installed, if you installed all the npm packages, called AxiosRetry. There's also a way to handle it via the interceptors. So, if you intercept the request and actually provide a function here instead of error and do the retry there, it's also possible to handle it here. However, when there is a library, why would you do it on your own, right? So, the AxiosRetry is actually already in your project, so you can just use the AxiosRetry and define how many tries you want the Axios to retry the request. And there is a retry delay. Now, typically, most libraries by default would do it in a way that they retry the first request, then they wait a few seconds, and they actually double the amount of time that they wait to save resources. So, that's what is the AxiosRetry.exponentialDelay. So, that's doing exactly that. In this case, in the AxiosRetry file, you're gonna see that we're using another function here. So, as the getflight's unreliable, if you're working locally, that's gonna work. If you're not working with the local endpoint, I'm just gonna fix it in a second, but this is the endpoint that I showed you earlier that returns a good response only once in five times. So, go ahead and try to do it there. I'm gonna add the code in here. So, this is the AxiosRetry, and it needs the Axios instance, of course, and then it needs the config. So, we're gonna do 10 retries and retry delay. Oh, exponential delay. And that should be everything that you need to do here. So, just save that, and let me fix the endpoint so that we can try this one as well. Cool. Alright, so right now it's building. In a second it should be available. Now let me just copy the URL. So, is this config added globally for all requests or just the current one? That's a good question, I'm not sure actually. We can try it though. We can try it, we can add another use effect here. And see if it does the same thing. Fresh data two, we get flights. Oh, but this will be a bit, oh, this is not ideal. Let me try it in the other one. So let me try if this works first, then we're going to try it with the console log that'd be easier. Oh, and I forgot of course to change the component. So we also need to change the component here from Axios intercept to Axios retry. Oh yeah, that makes sense. Binging. So, and now it's not working. Why is it not working? It's not working the course, but I already changed that. So it should work, but anyway, you see that it's really trying, yeah. Get flights unreliable should have all the right headers. Get flights unreliable, but still complaining. Oh, there is the, no, we don't need that here.

10. Troubleshooting and Axios Retry

Short description:

We encountered an issue with the headers for the 500 status code. After making the necessary adjustments, the application is now up and running. We implemented Axios retry, which allows the application to keep trying to retrieve data even when errors occur. Additionally, we introduced the axios-timeout component, which sets a timeout for two seconds and displays a timeout error message. However, this component only works locally.

Hmm. Yeah, exactly. So you can kind of see that it's waiting more and more and more. Do you set up course response for all endpoints? I did set it up for this one again. Get flights unreliable. Yes. It just did that. Now. Let me try and deploy it again. So I edited the headers for the get flights. Now I did that forget flights unreliable. Now I'm trying to redeploy it again. We'll see if that helps. But it should work. Ah, but didn't do that for, right. Okay, so there's the problem. So I did that. Actually, let's take a look at the function so you can avoid the same mistake. So I added the headers here for the 200 status code but they didn't add them here for the 500. So that would be the problem. Okay, so it should be up and running in the few moments. And let me show the code back. Okay. So now it's published, let's see. Okay, this is much better. So you see we're getting errors, but it keeps trying to get the data, and finally in the end we get the data here. So is that working for everybody? Let me know in the chat if it works for you. Hopefully that's perfect, it does. Nice, okay, cool. All right, so that's the Axios retry, and let's see. There is one last task here. Try to use the component slash axios-timeout. Now there is no task for you in that component to see the request actually timeout. So when you look at the axios-timeout component, the only thing it does is it has a timeout for two seconds and a timeout error message for timeout, and it's using the API endpoint get flights slow. Now that one will only work locally. So I didn't add headers for that. Let me fix that in a second, but again, just to swap the components in the AppTSX and it should all work for you.

11. Data Fetching with SWR and React Query

Short description:

We're going to explore the use of SWR and React query for data fetching and management. These libraries handle data fetching and provide features such as loading and error state handling, retry policy configuration, request deduplication, automatic revalidation, and paging and prefetching. SWR is a library developed by Vercel that focuses on data fetching and provides all the necessary features in a small bundle. We'll be using the useSWR hook instead of useEffect and provide a fetch function for the network request. Now let's move on to the next task and enhance the view for the remaining states.

All right. Okay. I just adjusted all the endpoints, so now all of them should be working also remotely. Let's see. Let me just go back to AppTSX and change that. XU's timeout. And. And of course I need to change the end point to the remote one. This is kind of what we expect. Yeah, excuse error, handle timeout, it timed out so we don't see if we don't see anything. We would have to handle the error somehow to provide a nicer message but the important thing is that we're not seeing coarse honestly here. It seems that it worked and the timeout actually prevents it from getting the data. If we actually make it more, let's say 10 seconds, it should start working. I saved that. Yeah, there it is. So it just wastes five seconds and then gives us the data. Okay, so that was the last bit here, kind of a bonus thing. And now we can move on to the more interesting part of the data fetching, and that's this part. That's the data management. If you wanna handle the data using a store, that's of course possible, but the libraries that we're gonna talk about, uses VR and React query, they actually handle all of these things for you. In case your components need to get the data and you don't want to manage that explicitly, you can use these tools to handle that. So fetching and managing the data, so far we always used use effect. Not sure if you noticed that, but it was always here. This means that when the React component is mounted, this will actually call whatever is inside only once, because there is the empty area as dependencies. So it will only run this once, but it will run in a sort of uncomfortable fashion, I would say. With useSVR, that's the other option that we have here. It gets much better because this was designed, it's actually a library that's implemented or developed by Vercel, and it's SWRS in state while revalidate. And it provides, it's really focused on data fetching, so it gives you all the status states and everything you need to also react on different states of the data loading. We're also going to use use query later, but first I wanted to take a look at still while revalidate, how it actually works. I got this picture from Google, because they have really great diagrams in this sense. And this nicely shows how still while revalidate works. So first of all, when you're requesting some data from the page, it tries to find that in the cache. So it's not doing the network request, if it finds it there, it provides that back to the page and revalidates it in the background. In this case, when the data, of course, when we've refer to page, the data are not in cache. In that case, we do the round trip to the server, then we store it in cache and then we provide it to the page. So it kind of saves the subsequent requests. And it also ensures that when you have multiple components that need the same data, they can or the SVR can do the network request only once and then let the components share the gathered data. So that's how the SVR works. It's the same principle as with the react threes. Yeah, they also store the data locally. Of course, later we can talk about how to mutate the data, how to refresh the data, how to proactively revoke the validity of the data and so on. But first I wanted to go over the SWR features. So as I mentioned, SWR is a library. You install it in your project and you use it instead of the use effect. So we can kind of compare the use effect with USE-SWR. In SWR in case of data fetching wins it on every point. I think it provides an easier handling of loading and error states. So it gives you the different states in a form of booleans so we can provide different front ends for each of those states. It has an easy configuration of retry policy. We're going to look at it in a second, but it's much easier than with Axios and with the interceptors. It provides the request deduplication. That means when you're loading multiple components on a single page that need the same data, it will only do the network request once. It provides features for automatic interval based interaction based or no revalidation. That means by default when you go to another tab and then go back to your page, it can revalidate the data automatically. It can also react on many other events that happen in your application. But as I mentioned here, it can be automatic, you can define an interval when the revelation should take place or you can actually prevent the revalidation overall. So depending on what your project needs. And then it has an ability to do paging and prefetching. It handles that in a very, I would say, easy and simplistic way. Than what React query does, for example. But we'll look at that in a moment. Good benefit is that it's bundle is relatively small, only 4.4 kilobytes. Much better than what we're gonna see for React query. But overall, I've heard from developers that this is typically the way to go because it provides all the necessary features for a really small, small bundle. But let's go to the next task so we can see how it works in reality. So, we're gonna use the useSvr hook instead of useEffect. And the good point here is that for the useSvr and for the React query, we're gonna talk about that in a moment, you always need to use either Fetch API or Axios, right? So, it's not gonna do the raw request for you, but you have to provide a fetch function, so-called fetch function, that will actually get the data. So, it doesn't care how you're doing the network request, it's in your hands, but you have to provide it somehow. So, we're gonna use the useSvr hook instead of useEffect. And we're gonna see how we can enhance the view for the remaining states.

12. Data Fetching with SWR

Short description:

The SWR function is used to fetch data. It takes a key parameter that serves as an identifier for the data. The flights fetcher function is an async function that uses fetch to retrieve data from a remote endpoint. The useSWR hook is then called with the key and fetcher function. The isLoading, data, and error states can be accessed from the returned object. If isLoading is true, a loading message is displayed. The same can be done for the error state. Finally, the SWR function is used in the component, and the data is displayed in a table. If the data cannot be retrieved, a retry policy is automatically applied.

So, you see that it's, the call looks like useSvr. First parameter is a key of the data. In most of the examples that you see online, you're gonna see, sorry for that. You're gonna see here an API route. Don't confuse this with the fetcher function. This does not mean that it's gonna get the data from that route. Here, you're only providing sort of an identificator for the data, only a key. And the flights fetcher will be a function that takes the data and provides that.

So let's take a look at the SWR. Well, this one also has some specs, so let's remove that. And you see the first thing is the flights fetcher function here. And it's an async function. Otherwise, it looks exactly the same as it used to before. I'm using fetch here, which means I'm also gonna have to add here the mode course. And provide the endpoint. If I want to use it remotely. But otherwise, you see, it's exactly the same. We're returning the data, we're doing a console log here, fetching data from remote endpoint, so that we can see it's only doing that once. And here we need to do the SWR call. So that will be use SWR. As I mentioned, first is the key, so that can be flights. It can, of course, also be slash API slash flights. If you want to unify that, I would actually consider that a good practice. To have that the same as the Fetcher function does, but it's completely at your discretion. So let's do all my flights here. And here we need the Fetcher function. So flights Fetcher. And, of course, this way we don't get the data in any way. So we need to, we can either do it this way. So we can call it like info. And we have all the data here in the info constant, but what we can also do, we can unwind this and say we want data, we want its loading, and we want error states. Yeah, otherwise it's all in the same object. So if you do it this way, or if you do info, and then do info.isLoading, completely up to you, I kind of prefer do it in one step. So let's do it that way. So this will actually get us the data.

Now, the good thing here is that we only have the table here, and we were always waiting just for the data to appear. What we can do now is say, if isLoading, we can return something like, so we're returning tBody here. So we're probably wanna be doing that so that the HTML markup is the same. You have five columns. And we're just gonna put here something like loading beta. And the same can be applied to the error. Then we turn tBody. We just copy paste that so I don't have to write everything. All right. And the last part as as usual, go back to aptsx and change that. So here we want to use swr from components. And let's see. Failed to load data, look at that. Fetching remote data from the endpoint. For some reason it didn't, like... Let me see what's the problem there. Oh yeah, this is the problem. No, we're in the wrong file. Swr fetch mode course. We have clients that should all work. Fetching data from the remote endpoint. We get that here. Why are we using swr retry? Using swr. Oh, okay. I have a wrong import there. It should be only swr. And there is a mistake in the retry file. There should be retry. Okay, so now let's see if we save that. Okay, finally, we get the data. And that's it. You see, if I refresh the page, you see it is loading data, then I get the data right away. And you also saw that if it cannot get the data from the endpoint, it's automatically doing the retry policy. So here you don't even have to set it up. It's working by default like that.

13. Using SWR for Data Fetching and Mutating

Short description:

In this part, we explored the use of SWR for data fetching. We discussed the benefits of SWR over useEffect and how it automatically handles features like caching, loading states, and error handling. We also learned about the mutate function in SWR, which allows us to invalidate cached data and force revalidation. Additionally, we added state labels to indicate when data is being fetched or when an error occurs. Finally, we tested the network request behavior by duplicating the component and verifying that the request only happens once. Let's now move on to the next task.

Now, of course we're gonna look at the retry in a second as well, in case you wanna change the behavior. But overall, this should work just like that. Know that when I was changing or when I was doing the Use as VR, I also added the mode course. So if you're using the remote endpoint, it's using the fetch. So the fetch needs the mode course here to get you the data. You can simulate the slow network connection in Chrome, I guess Firefox does that feature to under network tab.

Yeah, definitely. Yeah, we can do that. In this case, I'm not trying to do that though. Here I'm just trying to use the Use as VR. And for the other use cases, we actually have the other, to show the load in data message. Yeah, definitely. Yeah. I can do that. I'm not sure where that is, but I assume somewhere around here, let's say regular 3G. I always find this way too slow, but okay, it's maybe because of the image, but you see here loading data. Let's try that again. Yeah, for a regular 3G, this seems a bit slow. There we go. Yeah, good point. Perfect, so this is how the use of SWR works. Overall, it's much better because it comes with a lot of the features automatically. Yeah, and it's better than the use effect because this was really designed for that specific use case. So I would actually default to this one for any data fetching. Now, let's go back. Let me know guys if you all can see this, if you are at the same place or if you need more time, if you need more time, let me know. I'm not sure if that's fine. But I hope that we're fine. Okay. Flags fetcher calling unreliable instead. Yes. In that case, that was the mistake that I fixed here. So the SWR retry file had SWR here only. So if your Visual Studio picked it up just like mine did, then your import in app.tsx is wrong because it shows here SWR retry. So I'm going to change that to components slash SWR. Yeah, I didn't name the retry, of course. Yeah, that's what I did, actually. Okay, using SWR do you have to manually update the key if you want your fetcher to fetch something else? I would say it's a good practice to do that. Right now, you see that here in SWR, the key has zero relation to the flights fetcher because flights fetcher defines its route on its own. In ideal case, I would do it that way probably. And in the documentation, you also see the fetcher function as something that's very generic that only takes the argument from the first parameter and uses that for the route as well. So it probably would be a good practice to do it that way. Yeah. But it's not necessary. At the end, this is just the cache key.

Okay. I think that we can move on to another task. That would be the add state labels to let the user know when data are being fetched or error occurred. So that's the next part that I did with the labels. And you see, it's really easy just to, if it's loading and return what you want to return is error the same thing. And the last thing I wanted to try out is to duplicate the component in app TSX and check that the network requests happens only once. So it's actually really easy to test if you go back to app TSX and copy this a few times. Of course, you should see it a couple of times, but let me clear this. But you see that the network request only happened once. Okay. Okay. Now, let me know if we can move on from this. If you tried it. Yeah, you see that when I'm moving between tabs, it does that again. So whenever I tried to get back right now, I think I mentioned the time, but when I go here, here, you see, it's refetching that. So it's pretty aggressive with the refetching. Of course this can be configured if you wanted to behave differently. All right, so that was the task five. Now the task six is to mutate the SWR. The mutate function in case of SWR can invalidate the cached data. When we look at the button in SWR mutate component, it only needs to be, there's only a single button, HTML button, and we need to do the onclick event for mutate files, so that's the mutate function here. And when we do that, when we provide the cache key or the identifier of the data in cache, it will actually remove the data from cache and force it to revalidate. So let's take a look. It's in the components SWR mutate. So here's the button.

14. Mutating Data with SWR

Short description:

In this part, we explore how to mutate data using SWR. We learn that by calling mutate on a key, we invalidate the data in cache and trigger a refetch. This is useful when components rely on the data and need it to be updated. We also discuss the use of the SWR retry component, which allows us to implement a retry policy for fetching data. The component is already implemented, and we can simply change the endpoint to test different scenarios. Overall, mutate is a powerful tool for manipulating data in SWR and can be used for various purposes, such as updating, posting, or patching data.

You see this is the functional component that only has the button, nothing else. Let me just put it in here so it's a bit more visible. And let me just put the onClick here. So what we want to do is mutate the flights. And add the input from SWR. And I'm gonna edit below the table so that we can run this. I'm still gonna remove the extra components there and add the button here. It was the swr-mutate. Let's remove all that and refresh the page.

Okay, so we got the data from the remote endpoint. And when I revalidate, you see it's getting the data again. Automatically, yeah, because we still need to have the data here. So what happens if we use that in different components levels? Meaning, when I use the fetch-in app and also call it in subcomponent, but also fetch only once? Yes, in that case, it will fetch only once. That's actually what is called, we go back here a few times. Oh, where was it? Alexios, SWR features, here it is. So that's called the request deduplication. That means if both of these components need the same data and they ask for it, it will only fetch it once. Yeah, that's what we simulated on the main page when we added the component a few times. And let's clear that and we hit the Revalidate button. You see it's fetching data from the remote endpoint only once, but we have three components here that actually need the data and that are actually proactively trying to get the data from the network endpoint, but, you see, it does that only once.

So does the mutate receive fetch dependencies like params? What do you mean by that? Yeah. So when we go back to swr.mutate, this is the on-click event that I added. So it's mutating and only the flights. So this is the dependency or this is the key under which the data are in cache, and it's going to revalidate after that. All good, perfect. So when we go back here, I think this is what we already did. Try the retry policy implemented in swr by using the components, swr-retry component. So... I didn't understand what mutate is used for. Right, so in this case, by calling mutate and the key here, we're actually saying that this data that are stored in cache are no longer valid. So when we do that, when you click on that, and when we're mutating that, it's actually invalidating the data and it's fetching them again, because there are components that are relying on the data. So what it does is it will tell swr, this data are no longer valid, refetch it. Right. And you see that right here. It's still calling the fetching data from the remote endpoint. So it's going back to the component that we used and it's calling the flights fetcher again. Of course, there are advanced use cases where you can mutate the data also only locally and work with it. You can also use the mutate to post data into remote endpoints and so on. Unfortunately, I don't have a use case for that here in the scope of this application. But this is the easiest way you can invalidate the data. This is the use case that I wanted to show. But otherwise mutate is used to really mutate the data sets. You have to adjust the data, change the data, or even post the data or patch the data, whatever you can think of. This is just very simple use case that will invalidate the data and cause SVR to call this again. And eventually rearender the component as we get the new data. If that request has some dependencies that may have changed, maybe it should or shouldn't refresh based on that dependencies. Can you handle that with mutate? So in that case... Yeah, depends what you need to do. In that case, it will always refetch. If you call the mutate on this key, it will always invalidate and it will always cause it to refetch. Yeah. If you wanna only to change the data, I haven't seen that use case. I would have to check the documentation for that. I assume it's possible. But yeah, I don't know from the top of my head honestly. I would have to check the documentation for that use case. So mutate always forces the invalidation? In this case, yes. Okay. Okay. If there's anything else, then feel free to ask. We might need to check the documentation, but that's what it's for. And then the SWR retry. I really wanted to quickly show you that. This component is actually implemented. So nothing for us to do here. I'm just gonna only change the endpoint. And put the course there again. And, okay. So what this does, and I think I also wanted to do the other endpoints to do the slow one, or the unreliable one. Because here we're doing retry.

15. Data Fetching with SWR and React Query

Short description:

The retry policy allows for repeated attempts to fetch data, with the interval set to every five seconds. SWR provides many advantages over useEffect, including built-in cache, request deduplication, and support for different Next.js modes. React Query is a more advanced alternative to SWR, suitable for pagination and infinite scroll scenarios. It can be used with other frameworks like Vue.js and Angular. React Query has more features and a larger bundle size compared to SWR. It offers automatic retry of failed requests, query cancellation, and initial clear data for static site generators. However, configuring React Query can be more challenging, especially with TypeScript types. Overall, SWR is recommended for most cases, while React Query is suitable for advanced use cases.

Yeah. The unreliable one. So that we can see how the retry works. Let me just go back to app and change that here. I can leave that there. So when we go back here, you see failed to load the data. And I think that the time was there like five seconds. So every five seconds he's trying to pull the endpoint. And once you see there are still 500 responses again and again and again, but hopefully in a second we're gonna get 200. So status didn't gain, right? So now we got the data. So you see that it's trying to pull like right now I changed in the implementation, changed that it's doing that every five seconds. So here we configured every five seconds. We could probably try to do it in another way or just leave the default behavior, which should do it as we saw with Axios. Every try it's trying to prolong the time when it's revalidating when it's sorry, retrying. Yeah. And you see again, came back to the tab and it's trying to refresh the data again. Right now we were a bit more lucky. When we cause the revalidation again, you see it's again trying to pull the endpoint. Okay. One more try. We're gonna move on. Okay. 500 maybe next time. So that's the retry policy.

And this is actually a table that I wanted to show you. I found it in one of the articles and I think it very nicely illustrates the differences between SWR and Use Effect and when it's actually beneficial to use one over the other. So you see that pretty much the only advantage of a Use Effect is that it's part of React core, which use SWR isn't, but overall SWR provides you with features like built-in cache, request deduplication, SSR-ISR-SSG support. So obviously it's built by Vercel so it supports all these modes of Next.js. It's able to revalidate on focus on network recovery. So that's actually something, if you don't have a good internet connection, like half of the internet is not working for you, if everybody was using this, it would actually start working, at least part of that. So it brings a lot of benefits and it's much, much better to work with also from the developer experience point of view. I'm gonna provide you the presentation later, there's also a link for the whole article, very nice read actually, so I definitely recommend that. And we can finally get to the React Query.

Now React Query is something like use-as-w-are, they share a lot of the same features, but it takes it to a next level. So with use-as-w-are, it handles like 80% of the standard data fetching use cases. With React Query, you would probably use that for cases for pagination, infinite scrolls and these a bit more advanced scenarios. React Query has a great documentation but it's at some things, it's also really hard to work with and get it, fine tune it so it's configured in the right way. So I would definitely advise go with use-as-w-are most cases and use React Query if you need advanced features and there it doesn't matter if you spend a bit more time configuring it. But overall, it was formerly known as React Query right now in version four it's a 10 stack query. The good benefit is that it's not only for React. So if you work with also Vue.js or if you work with Angular or other platforms or frameworks you can use the same library there as well. Of course it's not the same code but it has it's alternatives, yeah. It has more features. There's a link, I'm gonna send you the presentation, yes. So there is a link for the four more features. It goes actually to the documentation of 10 stack where there is a nice view. I think this is the wrong browser. Let me... Let me copy that to the other one. Where it compares the React query with all the other possible frameworks that you could use. And it nicely shows where the features are. Some features are more important than others. It also compares the bundle size which is definitely interesting thing. I know that someone mentioned the Apollo client so you see that one is a bit bulky but it's useful for GraphQL definitely. So yeah, definitely a nice resource. Sorry for that. It also has automatic retry of failed requests but they use as WR has that as well. The configuration of those is a little bit easier here. It features query cancellation which means if a component is removed, if a component is unmounted before that the requests that it fired are finished, React Query can actually cancel those automatically. There is also initial clear data. This is very useful if you're working with static set generators and you want to have a, let's say you wanna have a listing but the first page of the listing you wanna generate them at the build time. And the other pages or if this is infinite scroll and then you wanna load the other data on a click of a button, you do it on the client side but the first the initial data can be there from the build time. So it has these like a very sophisticated features but as I mentioned, it's at least from my point of view, it's much much harder to configure. It's at some cases like with the infinite scroll that I mentioned, it's quite hard to get it right with TypeScript types. If you're working with TypeScript extensively, it's not easy to make sure that everything fulfills the notation that the React query needs. So yeah, I would say I would default to use as WR actually. The bundle size is 13 kilobytes, nothing that complicated I would say like when the bundles these days have hundreds of kilobytes. So I don't think this is the most deciding factor but it could be for someone. And let's go to the next task to use the React query. Now I didn't do any interaction, I'm not browsing the documentation because I think it's quite the usage is quite easy.

16. Using React Query for Data Fetching

Short description:

The React query component is already prepared and provides the same functionality as useSWR. It includes constants for is loading, is error, and is refetching data. Unlike useSWR, React query allows for distinguishing between the loading state and subsequent refetches. The query key remains the same, using the flights query function. Fetch API or XHR can be used to retrieve the data.

So we can do it together, write in code. You see that there is a component called a React query already prepared for you. And the call is pretty much the same as use as WR. It again has is loading, is error, is refetching data constants. You see that the is refetching, it's already providing you a little bit more data here. So with use as WR, we only have the is loading. When it was a refetching, it was still is loading. Here we can actually distinguish between multiple cases. Like the is loading is the first time, is refetching is the subsequent refetches. And otherwise, similarly, the query key here, you see it's still flights query function. This is again the flights features. So you need to use fetch API or X cos to do that and so on.

17. Implementing React Query for Dynamic Data Fetching

Short description:

Let's explore the code for using the react query library. We need to remove the suffix and use the useQuery hook. The query key is an object that allows for multiple keys in any order. The flightsFetcher function is used as the query function. We can add labels for loading, error, and refetching. After fixing the fetch, we can see the application in action and observe the appropriate labels based on the background actions. The labels help inform the user about the data fetching status.

So let's take a look in the code. So this is the react query. You have to remove the suffix and do that here. So again, the same thing as before data. I'm not sure how the rest is called. So I'm just gonna leave it as it is right now. And we're gonna use the use query.

Now for that, we're gonna need to use the fun stack react query import, and let's see. So we've got options here. I think the first one is the query key. Yeah. So this is actually an object, what we need to provide a query key, white. I don't see this as array. So it also has, I don't wanna get into that because that's very nicely described in documentation, but it has the possibility of having multiple keys. It's actually deterministic, so you can add them in different order. Not in the array here, but if you do like this, you can add multiple keys here in any order. So it's much more granular than what UXSW R offers. And I think you really need to do the query function, which is gonna be flightsfetcher. And that should be all that we need. If I'm not mistaken. Now, of course, there are no labels here.

So now when we have the use query here, we should be able to get into this sense. So let's see if we get that. Yeah, so it's loading. It's refetching. And I think we used error as these keys. So again, just like we did it with SWR, these two labels, we can do them here as well. So it's loading error. We can do another one for, it's refetching. Okay. We can do refetching data. And of course I'm gonna have to fix the fetch again. And switch that into app TSX. Okay. Try to remove that one. And see the application. Not this one, but this one. Okay, we can do the throttling again. Regular 3G. And refreshing. How come you're not using v5 of React query? I think it's not in v5, but we can take a look. Yeah, the time stack query is in v4. And it was previously known as React query, but that was a version 3, if I'm not mistaken. Let's see. Where, I read that somewhere. Maybe here. Somewhere there was an overview that shows that, but the v4 is time stack query. I don't think it's in v5. Yeah. Okay. Okay. So, yeah. So here you can actually see that it's doing the loading data label. Okay. Okay. This is taking way too long. Okay. Here we go. So these are the data. And when we go back to the tab again, you see that it was the re-fetching data. Now this is still too quick, but you can kind of see that re-fetching data. So it's not doing loading data, but re-fetching. So we can maybe do GPRS, maybe that'll make it yeah. So now re-fetching data. Yeah. So you get the right label depending on what kind of action is going on in the background. So that's that. And yeah. Let's stay labels to let the user know when data are being fetched, loading re-fetched or error occurred. So that's what we did.

18. React Query Pagination and Final Remarks

Short description:

The React query pagination allows for displaying or hiding next and previous buttons using the isPreviousData state boolean. The query key includes the page parameter, which can be incremented or decremented to retrieve different data. The React query is useful for advanced use cases with pre-built initial data, but it can be challenging to configure correctly. There are many features we couldn't cover in this workshop, but the choice between useSWR, React query, fetch API, and Axios depends on the project's needs. It's recommended to choose the one that best suits the specific use case. If you have any questions, feel free to ask in the chat. This concludes the workshop, and if you want to get in touch, you can find a link to the speaker's Twitter and Discord server in the presentation. Thank you for joining, and if you're in London next week, visit our booth.

Hopefully this works for everyone. Let me know if you need more time. Otherwise we can move on to the last task.

Okay. I think we're good to go. And the task is actually not here. The last one is just a question how to choose the best one. But I still wanted to show you one more thing here with React query. And that was the react query pagination, which is in the component right next to it. So feel free to take a look and add it to the app TSX. So here, what it does is apart from using the isLoading, isError, isRefetching, and so on. There is also another very comfortable thing isPreviousData. So that's another state thing, that state boolean, that we can use to display or hide the next and previous buttons. So this example actually, the only change here is that it provides a total count of data from the getFlightsPaged. Otherwise, it's still the same data, only it returns it based on a page and returns that back to the React query. Now you see that here, in the query key, we're also using the page. So the page is by default zero, but if we increase that with the button, which is all the way down here, page plus one or page minus one, we're getting a different data. And the query function is still the flights fetcher. And based on the existence of data, here you see isPreviousData, we're showing or hiding the buttons. Well, not actually hiding, but disabling them. So when we change that in the FTSx again, for one last time, React query pagination, and actually have to fix the endpoint again. Well, actually, let's use just the domain. Let's switch off the throttling. So here you see that we're getting the flights. Current page is one, and we see the buttons previous and next page, right? When we go to the next page, it's giving us the next data. And when you arrive at four, at page four, because there are only 10 flights, when we arrive at page four, we cannot go next, because right now there are no more data. So the React query is really good in these cases when you really want to, or you can use all the state booleans that are there for more advanced use cases, as I mentioned, with the pre-built initial data, and so on. It's really good for that, but it's quite tricky to configure it correctly. Remove the comments. Did I leave a comment somewhere? Oh, here. It shouldn't matter, actually. But yeah, definitely, good practices to remove it. Now, of course, there are a ton of other features. We couldn't possibly cover them in this time. We could do workshop only on features of the React query. But that brings me back to the final question, how to choose the best one? And if you Google this question, and put there the use as WR, you put the React query, you put there maybe fetch API, or anything like that, you're gonna see so many threats with so many opinions. So I wouldn't wanna be the one that tells you, use this or use that. I actually, in my own projects, I default to use as WR, because that's the easiest one to use and easiest one to configure. And between fetch and Axios, I use fetch because it's native. But I would say like, you can use the one that fulfills the needs of your projects. And I think that we went through the benefits of each. I think you have a good idea now, which one is useful for what use case. So I would say, pick the best one based on your project. And if you have any questions, then feel free to send them in the chat. Otherwise this is the last part of the workshop. So if you wanna get in touch, definitely do that. This is a link to my Twitter, but we also have a Discord server. So we're gonna share that in the presentation as well, which I'm gonna send to all of you, or I'm gonna ask the organizers to send that to all of you. Yes, I can show the previous slide, this is the one. Sorry, there it is. Otherwise, thank you very much for joining. I hope you had fun. We had some problems in the beginning, I'm sorry for that, but it wouldn't be a good workshop without some life debugging, you know. And yeah, as I mentioned, if there's anything I can help you with, then feel free to get in touch. Otherwise, those of you who will be in London next week, make sure to stop by our booth.

Watch more workshops on topic

React Summit 2023React Summit 2023
71 min
Building Blazing-Fast Websites with Next.js and Sanity.io
Join us for a hands-on workshop where we'll show you how to level up your React skills to build a high-performance headless website using Next.js, Sanity, and the JAMstack architecture. No prior knowledge of Next.js or Sanity is required, making this workshop ideal for anyone familiar with React who wants to learn more about building dynamic, responsive websites.
In this workshop, we'll explore how Next.js, a React-based framework, can be used to build a static website with server-side rendering and dynamic routing. You'll learn how to use Sanity as a headless CMS to manage your website’s content, create custom page templates with Next.js, use APIs to integrate with the CMS, and deploy your website to production with Vercel.
By the end of this workshop, you will have a solid understanding of how Next.js and Sanity.io can be used together to create a high-performance, scalable, and flexible website.
React Summit 2023React Summit 2023
154 min
Localizing Your Remix Website
Localized content helps you connect with your audience in their preferred language. It not only helps you grow your business but helps your audience understand your offerings better. In this workshop, you will get an introduction to localization and will learn how to implement localization to your Contentful-powered Remix website.
Table of contents:
- Introduction to Localization
- Introduction to Contentful
- Localization in Contentful
- Introduction to Remix
- Setting up a new Remix project
- Rendering content on the website
- Implementing Localization in Remix Website
- Recap
- Next Steps
Remix Conf Europe 2022Remix Conf Europe 2022
162 min
Crash Course into Remix & Storyblok
You may read already about Remix. You probably already used it, and recently you may hear a lot about the headless CMSs. In this quick course, we will put all the pieces together, and I will show you why Storyblok in combination with Remix is the best combo for your next project. Stop by and try it yourself!
Table of content: 
- Introduction to Remix, atomic design
the headless world
- Environment setup
- Creating pages and understanding how the dynamic routing splat routes works
- Future tips and Q
Prerequisite(s): Node.js installed, GitHub account.
React Summit 2023React Summit 2023
91 min
Crash Course Into Astro, Kontent.ai and Portable Text
During this crash course, we’ll create a new project in the headless CMS, create the content model and data using the Kontent.ai CLI. Then, we’ll use the content to build an Astro website including front-end components and rich text resolution using Portable Text.
This will be hands-on workshop, you’ll need VS Code, Git, NPM and basic knowledge of JavaScript. Don’t worry, I will explain all the steps as we advance through the workshop and you will be able to directly ask any questions.
React Advanced Conference 2021React Advanced Conference 2021
159 min
Building Modern CMS Driven Web Applications with Strapi the OSS Headless CMS
In this workshop, we'll build out a fully functional website and integrated blog with Next.js and Strapi.
Table of contents:
- An introduction to Headless CMS and supported architectures
- Getting up and Running with Strapi and Next.js
- Integrating Blog functionality into a Next.js app
- Deploying your Next.js and Strapi Apps Bonus
- Implementing content previews with Next.js
Basic React Knowledge Basic knowledge of Node.js and npm Basic Web Concepts.

Node Congress 2022Node Congress 2022
134 min
Deploying a decoupled restaurant review site to production with Strapi and Platform.sh
Node.js has become an increasingly popular language to build and deploy backend APIs. In a world of legacy CMSs adopting decoupled implementations, plenty of frameworks have sprung up to classify themselves as "headless" CMSs, designed from the start to provide an easy way to personalize content models, administer permissions and authentication, and serve a content API quickly.
Strapi, one of the leaders in this space, has recently released their v4 version of the framework, and with Platform.sh it can be deployed alongside a number of frontends within the same project, giving a drastically simplified development experience working with decoupled sites. In this workshop, we'll deploy a Strapi demo application, which has been configured to serve a restaurant review site.
Piece piece you will add database services, tests, and frontends, all within the safety of isolated development environments. At the end, each user will have a functioning decoupled site, and some greater understanding of working with decoupled sites in production.

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

TypeScript Congress 2022TypeScript Congress 2022
10 min
How to properly handle URL slug changes in Next.js
If you're using a headless CMS for storing content, you also work with URL slugs, the last parts of any URL. The problem is, content editors are able to freely change the slugs which can cause 404 errors, lost page ranks, broken links, and in the end confused visitors on your site. In this talk, I will present a solution for keeping a history of URL slugs in the CMS and explain how to implement a proper redirect mechanism (using TypeScript!) for dynamically generated pages on a Next.js website.
Add to the talk notes: https://github.com/ondrabus/kontent-boilerplate-next-js-ts-congress-2022 
React Summit 2022React Summit 2022
21 min
Remixing WordPress: Building a Headless Site with Remix, WPGraphQL, and Web Fundamentals
One of the largest draws of headless or decoupled WordPress architecture is that we can endlessly remix the WordPress CMS that content creators love with the latest and greatest of web technology. This presentation will demonstrate how quickly a developer can get up and running with headless WordPress development using the Remix full stack framework. Using open source tools like WPGraphQL and Atlas Content Modeler, you can transform your WordPress site into a powerful headless CMS that serves data via GraphQL. We’ll see how we can query for and use that data in a Remix app, and also discuss how the framework’s focus on web fundamentals can benefit both the developer and the visitors who use our sites.
React Summit 2022React Summit 2022
20 min
Large scale projects challenges (NextJS - Contentful)
NextJS is an excellent full stack framework. Contentful is a well-known flexible headless CMS. Together are a great match, but when we talk large scale projects the challenges are completely different than the ones you may face in a small to medium scale project. Leonidas will try to raise your awareness on such challenges based on Greece's experience on redesigning Vodafone's site to create beautiful self-serve and guided journeys for Vodafone customers.
GraphQL Galaxy 2021GraphQL Galaxy 2021
23 min
Exploring the WordPress Graph with Next.js & WPGraphQL
Headless Wordpress using its built-in REST API is a powerful solution to scale WordPress to the web, but complex relationships can easily turn into chains of requests, making maintainability difficult along with the potential cost of performance.
With WPGraphQL, we can harness the benefits of GraphQL, leading to a better developer experience and optimized request logic, making sure we’re only delivering what we need to our users.
We’ll explore these advantages and how these pieces fit together with modern tools like Next.js to build great experiences for the web.

React Finland 2021React Finland 2021
24 min
React Bricks: a CMS with visual editing based on React components
Headless CMSs are great for developers, but not for content creators.
React Bricks is the first CMS that is super-great for Developers (it's just React, backed solid APIs), for Content Creators (it keeps the visual editing experience of no-code tools like Wix) and for Designers (you can express your exact design system and be sure nobody will break it). I'll show you how it works!