How to use SWR in React Native - Fetch and Cache data (tutorial)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's up not just developers welcome back to a new live stream and today we're going to learn about data fetching using S SWR in Rec native but first what's awr this is a lightweight data fetching Library built by the same team uh as next GS by by the versel team and some of the things that I liked about aswr is that it's really fast it's very lightweight compared to other Alternatives it's quite reusable it has a built-in cache and it automatically duplicates uh similar requests that are being sent to the API it offers real-time experience and uh it's really simple it only has one main hook that use S SWR that allows you to do all the fetching all the mutations everything in the same place it's also backend agnostic so it supports both Ming rest apis and graphel apis and today we're going to see both of them and as I said it's built by the team behind next GS so in this tutorial we're going to give it a try and we're going to see how uh explore the power of sswr in react native by building a real application and by experimenting with this uh Library this video is brought to you by IBM stabs and which is the easiest and best way way to build and um deploy graph Co apis we worked a lot with IBM staben and uh what I really like about them is that with one simple CLI command steps and import you can automatically create your graphql apis and connect it to your data sources being it SQL backends rest apis or other graphql backends this way you can connect all the data sources in one central location using graphql if you're interested to learn more about that you can check out our tutorials on this channel and one that I really recommend is the ultimate workout tracker where we used these Technologies but now back to today's video back to today's topic which is s SWR in react native if you're ready let's roll the intro and let's get [Applause] started all right right and if you're new here hello my name is Vadim and my mission at not just daav is to help you build impactful mobile applications on this channel we do a lot of Project based tutorials where we learn by doing and by building fun applications so if you're interested in learning rack native and other Technologies make sure to subscribe to the channel that will help us a lot now uh hello everyone who is joining us in the live chat and let me know where where are you joining us today from um and with that being said let's go ahead and start our tutorial because we're going to have a lot to do today and a lot of new and exciting stuff to learn that I cannot wait to share with you so here is some of a demo that I Was preparing for today that is fetching data using the uswr hook now I'm going to close this window let's pop up a terminal to start from from scratch so that everyone is on the same page and you can follow along together with me because that's the best way you can actually learn so I'm going to go into the project Z3 like this and when you navigate to a folder where you keep your projects let's start by creating a new Expo project I'm going to do that with npx create Expo application and um yeah let's call it s SWR the create Expo application is a tool that will bootstrap will initialize a br a blank Expo project uh and for that you don't really have to have a lot of things installed on in your environment so if this is the first time you're working with Expo or react native don't worry I'll cover all the basics and fundamentals uh so that you can um follow along together at this moment all you have to have on your system is nodejs and npm and then with npx create Expo application you can initialize your first Expo project now we're going to wait for nbm to install all the dependencies to set up a project uh after a lot of warnings and deprecations which is the usual stuff our project is ready and we can open it up in our uh editor of choice in my case that's visual uh not Visual Studio yeah Visual Studio code and uh I open here the project I'm going to close the terminal I don't need it anymore and actually the first step before we run the application I would like to uh switch from JavaScript to typescript even though you don't have to do that uh I think in some cases um it's going to help me uh show like the possibilities of typescript using S SWR to switch from JavaScript to typescript let's find the app.js file and rename it to up. TSX and then when we open a terminal and Run npm start to start the Expo development server Expo will see that we have a typescript file and will ask us if we want to install and set up typescript let's press enter and now xpro will install typescript will generate the TS config and our application or our Expo terminal is ready for us to start working at this point if you don't have a simulator or emulator on your system all you have to do is download the expoo application from the market scan this QR code and you're going to see the application on your physical device in my case I'm going to press I in this terminal to open it on iOS simulator and shortly it should update with a newly built project let me make sure that's the case so let's press I to open it on iOS it's going to also work on Android so you can press a if you have Android emulator and just like that here we have our new application uh the whole application that we have here is a very empty and blank application and everything is contained in the app. TSX TS x file here if we go ahead and find this text we can go ahead and change something to hello world save if the changes are automatically updated uh on our device then we are good to go to the next step um let's actually go ahead and continue uh by installing and setting up svr and seeing how we can send our first request so to to do that that go towr dovel doop and here is the page for this let's go ahead in the documentation and let's follow the getting started guide here I'm going to choose uh npm and all we have to do is install s SWR so I'm going to pop up pop a terminal um in this terminal we have our Expo uh development server running so I'm going to press plus to open a new terminal from where I can go ahead and run npm iwr this will install the package and we are ready to use as s SWR so the first step is to define a fetcher function a fetcher function is going to basically Define how do we want to fetch data so in this case we are simply using the fetch API which is provided in our re native environment in her uh environment uh but we can replace this Fetch with axos and with other Fetchers for example when we have to fetch graphql we're going to start with a rest API so this fetcher that simply calls the Fetch and then returns with Json response is going to uh help us get started let's go back to the documentation and now we can go ahead and um looking at this example we can start by importing the hook use aswr as I said this is the most important hook and I would say it's the only hook there are a couple of hours uh that we're going to see today but for like data fetching mutation we're going to use the use aswr so let's start by importing at the top of our up. TSX by use Sr from s SWR and this is actually a default export so everything is good now inside our application that's where we will do our fetching so let's go ahead and Define uh start by defining the use S SWR uh hook the first property of use sswr is going to be the key or in this case is going to be the URL to which we want to send the request in the example it's uh it's this playing it like this so I'm going to show it like this but it's going to give us an error I'm going to explain it shortly and we're going to fix it together so this is the first uh the first variable in for this hook which is as I said it's the key or in this case it's the URL to which we want to send the request the second parameter is going to be the fetcher basically how do we want to fetch this request now we're going to provide the fetcher function that we Define at the top which we simply call fetch by passing the arguments which in this case is going to be this URL and then it will return the Json response now that's everything we need to do to fetch something the use S SWR hook will give us three uh important things back and you might be familiar with these three things from other fetching libraries like R query and so on so these are the data which will be undefined initially and after the fetch after the data comes from the server this data will contain the response it will contain is loading to indicate if we are currently loading the uh the request and it will contain the error if something went wrong in this fetcher is going to be provided to us in this error so having this free uh we can go ahead and return different things on the screen for example if it's loading let's go ahead and return a simple activity indicator which is imported from react native here at the top and will be a simple spinner however if it's not loading but if there is an error in that case we want to probably return a text saying uh failed to fetch data and then we can even show the error Dot error or error do message and if it's not loading if it's there is no error that means that we have data so for now let's go ahead and console uh log the data but in order to see it properly in our terminal I'm going to do json. stringify I'm going to passware data and by providing here n and v two it's going to uh properly structure and um do the indentation for us so we can easily see the data in our terminal okay so far so good but the problem is that we see something there like at the top of the screen we see failed to fet Data Network request failed uh before I get into the issues of that what I'm going to do is I'm going to import a component from R native called safe area View and I'm going to go and replace our root view with a safe area view by doing that and make sure the closing tag is also safe area view by doing that our error message should be displayed in the safe area view why it's not that's uh that's a bit too strange save area View oh yeah yeah yeah because the error itself is being uh returned here as a text so what we can do is maybe we can copy the safe area view to wrap our error inside the safe area view like this make sure to properly open the brackets and when you start the return return then add the safe area View and then the text uh so now we are going to see fail to fetch Data Network request failed well that means that we've got an error by sending this F request that's uh obvious because we do not have any API running on our local host at the moment that will um handle this request in nextjs you can easily do that in Expo using Expo router you can create um um an API route that will make this request work but I'm not going to focus on that I'm not going to focus on API routes today so for that reason I'm going to replace this local request with a request to a remote rest server also I don't want to get into a lot of details about building a server so we're going to use a server called Json placeholder that you can find at Json placeholder Doty code.com and this is a simple API that we can use for testing purposes what I'm going to do first I'm going to go to this post request and as we see if we send a request to this Json Place CER SL poost we're going to get a list of posts let's copy the URL at the top let's go back to our terminal and instead of this uh route or instead of this end point we're going to fetch actually the Json placeholder do typy code.com posts now we no longer see the error fail to fetch data we see hello world that means that uh and another thing is that if I'm going to refresh our application by pressing RR two times we should see a loading in and the activity indicator but it should be at the top and it should be very very fast so if you want to put it in the center of the screen maybe we should also wrap it around this safe area view like this so now if I'm going to refresh we have that loading indicator for a very for a split of a second and then it goes into hello world that means that initially when the component mounts the is loading is going to be true we're going to render the activity indicator and after the request success succeeds we're going to get the data and we're going to get here and render the hello world also in the console we are logging the data itself so if I'm going to open up back the terminal and go back to where our Expo terminal is running we see uh the array of posts being fetched from the server perfect so with that uh we have a very simple request made uh using the use S SWR hook but this is just the beginning uh we're going to continue and you're going to see like the the value of this hook shortly but as you can see from the GetGo the whole implementation is quite simple like there is not a lot of things going on so that's that's what I really like about it all right so uh moving on let me check the chat to see what are you guys saying I'm going to put it here hello Hanan hello from Nigeria hello what is s SWR is it using in real world application so as I was saying s WRR is a fetching Library created by the next GS team by verel um it's gaining a lot of popularity recently it's really lightweight compared to Alternatives like T query uh it's at around 30k stars and today we are exploring how to use it uh Shivam saying switching to S SWR because react queries dropping one success and other call backs uh can you send me some information about that about dropping the own success maybe they are restructuring it hello from Angola hello coldon hello jokery hello aness Cornelio hello Tommy how are you doing guys anyway let's go back to our application and I would like to um to render something on the screen to make this a little bit more interactive for us to see visually what's going on because we see that we have data in the terminal but I would like to render something on the screen so let's go ahead and create uh a component that will render one of these posts the post has a title and a body so that's what I want to do and for that I'm going to go ahead and um should I go ahead and do a g status let's do get add so that you can see the progress set up S SWR now let's go ahead and render this post on the screen for that I'm going to go ahead and create a new uh folder uh called SRC where I'd like to keep all the source code and in this folder I'm going to create another folder called components inside the components I'm going to create a file called called uh post list item that will represent one post inside the list and here and here let's define this post list item as a functional component so const post list item is equal to a function that will return something on the screen most probably it it will return a view which is a container and maybe two text box for title title and another text for body let's make sure to let's go ahead and render a flat list a flat list is a component that helps us render lists of data and the two required properties is the data itself which should be an array of items so in our case that's going to be our data uh field that we get from s SWR after fetching the posts which is an array of posts uh and another property of flat list is the render item the render item is a function that specifies how do we want to render every single item from this array so for every single item we want to render a post list item like this so just like that we have a lot of title body things um on this page uh but let's go ahead and send the actual item that we are rendering here in flat list as a property to the post list item so that we can dynamically render the actual title and the body of those posts to get the item that is currently being rendered we can take it here by destructuring the item from the render item function and we're going to send it as a property to post list item called post equal item now let's go to the Post list item and receive this property in the function uh definition here in the props and it's called post so now we can go ahead and replace the title with a dynamic field called post. tile now we already see something on the screen and the body with post. body and we also see some data there now it's time to style a bit these uh components so let's import a stylesheet from Rec native and let's define the Styles below the post list item component const Styles equal Styles sheet. create and here we're going to have three Styles The View itself will have a style called styles. container the title I'm going to copy it from here will have a Styles Dot title and the body will have styles do body uh I don't think I want to spend a lot of time styling this so I'm going to copy the styles that I have prepared previously and what it does it says the background color of our container it makes the title bold and a bit um increases the size so we can clearly see what the title what's the body and reduces the color of of a body nothing too fancy now that we have some Styles here on the on the post itself I'm going to go back to up. TSX I think I'm going to add some spacing between the items in the flat list by providing the style of the container using content container style property on the flat list and if we specify here gap for for example 50 that will add 50 pixels between every item in the in our list I'm going to reduce it to 10 and to also differentiate like between posts I'm going to change the background color of our page from white to a ghost white like this and now there is some spacings which are very light gray between the items themselves and in the content container style besides the Gap I'm also going to provide a padding 10 to make sure that our cards we have some spacing on the left on and the right and with that we have a nice list of posts that are being fetched from the Json placeholder API using use S SWR hook okay perfect I don't think we need console log anymore because we are actually using those that data array and rendering it here what I'm going to do now is let's do git add git commit render posts perfect moving on looking at the documentation of uh s SWR in the getting started the next step they recommend is to make our data fetching logic to make it reusable and the benefit of making it reusable is that we can use the same hook to fetch the same data in multiple places in our application and then like we don't have to reinvent like all the hook definition so this is going to be done by creating a custom react hook that we are going to wrap around the uswr hook provided by this Library what does that mean let's go ahead and start by I think I'm going to start by going ahead and creating a utility function uh folder where I'm going to put this fetcher the fetcher is something it's like a utility that is going to be reused in multiple files so I'm going to extract it to a separate file inside a utility folder so let's call it utils and inside utils I'm going to create a function called fetcher. TS and in this function from up. TSX I'm going to move the fetcher itself the only thing is that I want to add the export keyword at the beginning to export this function so that we can Import in other parts of application for example back in our app. TSX if we go ahead and get that quick fix suggestion from V Visual Studio code it will tell us like that we have to import fetcher from Source utils fetcher now everything is working as it was working before but that's uh not uh the goal of our re reusability what I mean by the reusability is we want the whole like data fetching like this use S SWR hook we wanted to make it reusable and have a hook called use posts that will give us the actual posts for that let's go ahead in the source and create a new folder called hooks inside the hooks I'm going to create a file called posts. TS and here let's export a function uh so basically a hook is a normal function uh the rule of AR is to call it to to prefix it with use to define that this is a hook but it's not actually necessary it's only like a guideline so let's call it use posts and this is the function what makes it a hook that it will return some data for example now let's go ahead from up. TSX and bring this data is this use svr bring it from our application to our hooks post here at the top it needs the fetcher so let's make sure to import fetcher and also let's make sure to import use use S SWR from s SWR now having this data is loading an error we're going to return them basically in the same structure but I want to rename data to actually posts because these are actual posts let's do post is going to be equal to data then is loading an error I'm going to leave them the same so that means that now I can use this custom hook inside our up. TSX first we need to import use post from Source hooks posts and here instead of the use S SWR hook I'm going to switch it to use posts it returns is loading it returns error but it doesn't return data it actually return posts themselves now make sure to take the post and replacing the flat list with posts and all of a sudden everything is working as as it was is working before we can clean up some of the unused import like the fetcher the use S SWR from here from our app. TSX and just like that in our application file like where we need data the the logic where the API is very simple we simply call a use posts custom hook that is giving us fre Fields Back is loading error and posts if we look at that hook the implementation or the details of how it's doing the the requests are being specified here using the use sswr that means that we can use this use post hook in multiple places in our application and we will get the benefit of s SWR um for duplicating our requests I think we're going to see that right in the next step for now uh the um our goal was to make data fetching really reusable and we accomplished that using a custom hook perfect let's go ahead and do git add git commit like that okay everything good so far guys hello from India hello rames hello King gray thank you very much watching from Liberia hello Tyler from Ghana hello Randy all right guys so as I was saying this reusability will make will will bring us some benefits but at this moment we cannot see that because we only are quering the post in one single place um in the next step what I want to do is uh let's go to adjacent placeholder first of first of all if we go to the posts endpoint you're going to see that besides the title and body the post also has a user ID this user ID represents the yeah ID of a user now to get the information about that user we can call them slash user endpoint which by default will give us all the users but if you add a uh question mark ID equal one here it's going to filter the users by ID or maybe actually not question mark users SL1 yeah user SL1 is actually going to get our user with id1 and not as an array but as an object because it's only one user so um knowing this knowing that every post has a user ID and sending a request to the SL users SL1 where SL user slid we can get information about that user what I want to do next is I want to add the user information for every post that we see here on the screen okay let's start that by defining now right away a custom hook that will um fetch a user by its ID for that I'm going to create a new file in the hooks called called users. TS now let's export function use User it's not going to be use users because we don't need like the array of users we only need one specific user and because we need one specific user we also need to know its ID so for that reason our custom hook will also have some parameters the ID of a user that we want to query and if we look at the API our IDs are simple numbers so I actually typed it with a number type now uh we're going to let's practice what do we need to fetch the user well we need the use S SWR and the fetcher so let's import fetcher from our UTS and also let's import use S SWR from s WRR now we're going to get some data is loading an error from the use aswr hook remember the first uh the first parameter here uh is going to be our URL and the second one is going to be the fetcher and our fetcher expects with the argument is a URL that we want to fetch so let's go back to our Json placeholder and copy the URL um from here which basically is Json placeholder do typo.com users1 this one is should actually be a dynamic field so for that reason I'm going to transform this from a normal string to a template string using this back ticks and instead of one using the syntax dollar sign and Open corly brackets I'm going to provide here a dynamic field a dynamic variable the dynamic variable that we want to use in that URL is going to be the ID that we are going to receive when calling this hook and just like that we should have this information let's go ahead and return it back to the component that will be using the hook using we're going to rename data to user and we're going to leave is loading an error the same way now we have a reusable hook that can fetch data about a user by specifying the ID of that user well let's go ahead and test this hook and see if it works where do we need to fetch information about users we need that in every single post list item because remember if I'm going to do console log post the post will also have a field called user ID so using this user ID we can fetch user details to fetch user details we created a custom hook called use user that expects the ID of that user the IDE of that user we're going to take it from the post and as we saw here it's called user ID like this now back we're going to receive a user we're going to receive is loading and we're going to receive what else the error maybe we don't need like all of them but let's see what do we have here in the user if we check scroll to the end all right we see a lot of information about that user like his address but what I'm interested in is in his name so user do name let's go ahead and render it above the title in a text box in a text component by rendering user.name because user can also be undefined at the moment of requesting it I'm going to add a question mark here to safely access the name of a user only if a user is defined so just like that our post now contains all also as the first line the name of that um who of the person who posted that post the first ones have the same name but as we will scroll we see that we get other users as well now now we are going to see the benefits orever power of um s SWR uh first of all if we're going to look into the up. TSX into this post and if I'm going to do a console log post. length we're going to see that digit 100 that means that we have 100 posts in our list that also means that we are rendering 100 post list items every post list item is fetching information about a user so you would expect that we are sending 100 requests to the server to get information about the user of a specific post well that's not the case because in the use user we are using the S SWR and S SWR is smart enough to D duplicate similar requests and you cach the data and use that cash data instead of sending multiple requests with the same key because this is the key and when we are sending the same request to the same key meaning the same user ID is going to be cached and reused so in fact let's go ahead and check how many requests actually reached the server to do that go back to your Expo terminal and when you have a lot of flogs you can simply press C to clear out the terminal and here we can press J to open the debugger press J this should open uh this debugger and we can go ahead in the network tab the network tab will show us the requests to the network that our application is making so let's focus on our emulator and press RR to reload it now here we see all the requests that our application has made and I'm not sure how to zoom in here why I cannot zoom in okay anyway uh what we see here is we see the first request to our SL posts which gave us 100 posts and we only see five requests toward if we look at the headers towards the user endpoint user SL1 user SL2 three four and five and that's it we don't see 100 separate requests we see only five requests and that's because we this API only has this amount of uh okay okay I'm going to explain that in a moment this amount of unique um users if we start scrolling like new posts are being rendered on our screen so we start seeing more requests and sometimes it's actually um uh request towards the same endpoint for example we see the user with id7 is being requested two times and so on uh that's because there is a a time frame in which their requests are duplicated meaning that if you're sending multiple requests in a very short period of time then most probably the data behind is not going to change so s SWR will cash and D duplicate them but if you send a request now and then after a minute you send another request in that case s SWR cannot be sure that the the data is not uh has not changed from that moment so what it will do in fact it's what it will do is uh explain by the whole s SWR concept aswr stands for stale while revalidate which means that firstly aswr will return data from Cache I'm sharing here the code so on where homepage s SWR stands actually for stale while revalidate which is a very uh which is a concept from HTTP C cash inv validation so what that means is that s SWR will first return the data from the cache meaning that the data will be if there is some data in the cache for vet key it will be instant then s SWR will send the request behind the scenes to revalidate to make sure that the data is up to date and then when receiving the new data it will go ahead and update it on the UI so that's what we see here that's why we see that some requests are done multiple times because the time period between the request was a bit more than the D duplication uh configuration and all of these things can be configured and we're going to see that uh in a moment but the cool thing is that when sending multiple requests with the same key they are going to be D duplicated by default and automatically cached for us so that's that's powerful question is this like TCH query yes exactly this is an alternative Library similar to T query and they serve the same purpose um compared to T query uswr uh seems a little bit more lightweight and um and simple in terms of API meaning it doesn't have like all the possibilities that t query has but uh at the same time it makes it like really easy to get started and uh to to to work with it I was looking at someone was asking about like a comparison I think there should be a comparison here let me check yeah I don't remember I uh I thought there is a comparison on the S SWR page but I believe it's actually the other way around on T query there is a comparison uh with different libraries so you can go to T query and check this comparison table between tast query and S SWR uh so what I want to point out is the bundle side of s SWR is much smaller this is re query yeah so it's only 4.5 kilobytes then s SWR compared with 47 for Apollo and 14 for D query and yeah like most of things are kind of the same yeah s SWR has some some improvements like garbage garbage collection selectors offline mutation support okay yeah check out this documentation for more in depth comparison of it can you make a video on Rec native Expo off with with superbas and clerk uh guys all the ideas uh make sure if you have ideas to submit them on our GitHub slash I think it's not just Dev and if you go to the discussions and it should be a link in the description you can go ahead and leave ideas here so open a discussion into the ideas and you said Expo of with clerk that would be an interesting idea provide more details here of course and everyone else go ahead look for the ideas and vote for the ones that you'd like me to see Implement I'm going to look at the top ideas and I'm going to try to uh cover them in our future tutorials this is going to be a great way to make sure that what our community ons we're going to do here on the channel so make sure to submit the ideas on our board anyway let's move let's move on um yeah let me go ahead and commit everything get status get add get commit fetch uh user data perfect now uh I was explaining about the configuration of s SWR so let's go ahead in the get getting in the documentation and see what would be the next steps here this is the API and let's go to the global configuration with aswr config we can provide Global configuration that is going to be reused whenever we are calling this use S SWR so this is a great way to configure and set up everything once and forget about it also like as you saw so far we didn't have to create any providers we didn't have to do anything all we had to do is called the use aswr uh hook and everything go working that's really great because it allows you to get started really really quick but when you want to configure this globally uh you can do that uh at a global level in our case that's going to be at ab. TSX level so let's go here and what I'm going to do is let's import import something from s SWR and that something is called s WRR config is that correct yes now if we are going to wrap our whole return statement here you know what um I think what I want to do is I want to extract the the the logic of fetching and rendering a list of posts I want to extract it to a separate file that is going to represent our screen because right now it's in our app. TSX which is not exactly where it should be in our app. TSX we want to only configure stuff and then use other components or screens uh to to things so let me go ahead and create a new folder called up and this app will contain a file called uh post screen. TSX this is going to be the screen that we see here on this on our device and for now let me copy everything from up. TSX inside posts screen let's rename from up to post screen let's fix a little bit the import of our components by removing this Source because the relative puff should be double dots when components double dots to go back One Directory from our application inside components and also what I'm going to do probably is removing the safe area views because this will be left inside our application not inside the screen itself so safe area view safe area View and actually the status bar as well so rendering only the flat list now this post screen is much cleaner and it actually doesn't have any Styles as well um we can even clean up some of the Imports and now yeah as I was saying like this post screen is very clean like it only fetches it renders activity or error or it renders with flat list now back in our app. TSX what I'm going to do is I'm going to import post screen from source application post screen and instead of rendering a flat list here I'm actually going to render right away the post screen just like that and another thing is that now our application is not going to be responsible for fetching the posts that's the responsibility of our post screen so now our application is also very clean and we can clean up some of the unused things like a flat list and so on and everything should be good to go I'm going to Lo to make sure everything is still working by the way application uh is is a concept coming from uh exper router but at this moment we're not using exper router it's just a convention that that I'm using to keep up to keep my screens inside there okay perfect everything is going fine anyway now we have our up. TSX which simply render the screen andent post screen that is loading the posts rendering the flat list and handling the loading and error States okay let's go back to up. TSX let me actually do get add extract post to a SE separate screen I did that because in our app. uh TSX here we want to configure Global stuff and we want to to have it clean to configure s SWR globally as I said we are going to import from s SWR we're going to import s SWR config now let's go ahead and wrap it around everything here make sure to close the tag after the safe area View and we can provide here the value with the options with the configuration for our uh s SWR let's see one of the configurations that are is very useful is actually providing the fetcher globally so in vswr we can provide an object and here we can provide the fetcher that we can go ahead and import fetcher from utils now that we can we are providing this fetcher globally we can go ahead in our custom hooks for example for posts and we can skip providing the fetcher here making the use aswr hook even simpler by only having one parameter and if it's if this Hook is going to be inside the as config that provides a fetcher everything is going to work because it's going to use this fetcher same thing with the users we no longer need the fetcher here and the hook becomes even more clean now reload everything is still working perfectly and that's the S SWR config uh configuration on the global level you can also um Nest different configuration for ex example if on one screen you have different configuration you can Nest it and it will override the parent configuration uh this is good because the configuration not only provides the fetcher but can also have a lot of parameters providing information how often should it refresh how often it should uh D duplicate and so on here is a bit of information about nesting configuration so if we have an svr with this values and another one with updated it will override for that specific page this is good like if on some pages you have different rules for how data should be fetched you can also get access to this configuration using the use S SWR config hook if you need some information you can also provide a function to overwrite something and I'm really interested about what configuration we can set the context the global in the options so if I'm going to press here it's going to be it's going to navigate me back to the API and here we're going to see the options so these are all the options that we can configure for svr either globally or for a specific use aswr hook for example we can provide D ding ding I hope I'm pronouncing it correctly deding interval meaning how often do we want to D duplicate uh requests um so if we're going to provide here um on the svr the dupping interval of 2,000 which should be 2 seconds or maybe even more let's do 10,000 which is going to be 10 seconds in this case similar requests that are less than 10 seconds apart they will not be sent to the server they will be duplicated so this is how you can adjust these things I'm going to go back into the network and see if this in action I'm going to reload and now if I'm going to scroll I should see less the duplicated requests if I'm going to wait for a bit 1 2 3 4 for 10 seconds and then I'm going to scroll we should already start seeing duplicated requests because the time uh more time has passed than our didd interval and uh svr will go ahead and send the request because we are not sure if this is the most recent data anyway it will first give us the cach data and do the request behind the scenes so our UI will still be very very fast let's go ahead and scroll more here and we see duplicated request for example the six and the five we have above um and that's because more than 10 seconds has passed perfect um not sure like what would be like a rule of f here probably depends from Project to project um let's leave it to 2 seconds by providing a value of 2,000 milliseconds and you can go and see like more configuration that you can see here loading timeout can specify how much should we wait a request before we consider it um that it's time timeout there is on success call back function when a request finishes successfully on error on error retry so for example by providing on error here on the global configuration you can log this error with with using Sentry for example so you have um a way to globally U catch all the errors and log them with your logging solution perfect so that was our Global configuration let me go ahead and do git OD git commit minus M svr config for Global configuration but um I didn't mention that like these things these options they can also be specified for IND individual request as well for example I can go ahead and if I have here two seconds and if I'm going to go to them user I can provide here the I think the options yeah the configuration uh is that correct key fetcher and options but what if I don't have a fetcher what if I don't have a fetcher should I provide here null and then the configuration for example the dupping interval I can set it to zero for specifically used user so we can provide options for specific requests uh and they will override the global uh options that we defined in up. TSX here for example and let's see if it will work like this I'm not sure if this n for the fetcher will will work correctly but in this case we overwritten the theb interval of the on the users to zero so I expect all requests to be sent to the user so if I reload uh again we're going to see request and as we can see as we scroll the request are not duplicated or no they are maybe zero something else come on yeah now we see like really duplicated requests because we have overridden some of these options here so pay attention that you can do that here as well so all the options that you'll find in the API can be provided as the third parameter to we use aswr hook I'm going to remove them from here because I will keep using the global options perfect hi from Somali hello do you have any video about refresh token to persist users in your re native application um most probably we cover this topic in a lot of videos but I cannot remember like which exactly uh all right so uh we still have a lot of things to cover I want to cover the mutations when we want to update data and I also want to cover graphql how to request graphql apis and also some react native specific things uh related towr that we need to cover because they are quite important for example um when the application goes from background to foreground we want s SWR to automatically refresh data or revalidate data and by default it's not going to happen because we need to take some extra steps to um to make sure that this works in react native Environ so we're going to cover that in a second but first give me one or 5 seconds I'm going to be back and we continue all right right I'm back so um we saw so far how we can easily fetch data let's go ahead and see how we can mutate data using S SWR uh mutations uh are quite specific and these are operations that would will update some data being it in the local cache or remotely on our server so let's go ahead in the mutation and revalidation documentation and see how we can do that using S SWR so let's read it Sr provides a mutate and use Sr mutation apis for mutating remote data and related cache related local cache there are two ways to use the mutate API to mutate the data the global mutate API which can mutate any key and the bound mutate API which can only mutate the data corresponding aswr hook okay we're going to see what that means in a second how do we how are we going to do that let's first uh see the a global mutation let me check if we want to do something with specific data h trying to think of um use case uh to explain like both Global mutations and local mutations let's go ahead in upx above a post screen let's add a button list inside a empty fragment because we cannot return multiple um elements we need to return one that contains like children so that's why we need that one in order to render a button here button imported from react native with a title mutate and we see here at the top and let's define a function here const run mutation which at this moment will do a console Warr mutation let's call this function when we press the button so on press we're going to call run mutation now if I press the button we should see the mutation warning at the bottom that means that we correctly hooked the function to the button press event okay so let's go ahead and see how we can run a mutation using like a global mutate function to do that first of all we need to get access to that mutate function the recommended way is to get it using the hook use sswr config hook that we will import from s WRR use S WRR config now we have access to all the configuration and also to the mutate function now when we press this run mutation what we can do is we can call this mutate function and we can provide the key uh to the to the key that we want to update for example if we look at our existing qu Aries this is the key that identifies a request so if I'm going to take this key basically the same URL and put it here in the mutation and then provide a new data which is going to be an empty array I expect when pressing this button our list of post will disappear let's see if that's true if I press not sure what's happening maybe it was actually R run behind the scenes let's open the debugger to see what's going on there so debugger Network reload okay if I press mutate yeah it actually updates the mutation uh but then it invalidates it and sends the same request again so that's actually that's actually what we we are doing here we are saying that when something happens invalidate this request and what's happening behind the scenes it's going and finding like the request with that key and is running it once again because it was invalidated so if something happen in the back end we're going to receive new data Veer and we see this that the request was sent like one one more time here for the posts if I do it again it's going to be sent again so yeah this is also important when we do this it will only like I'll paraphrase what is written here so using Global mutator only with a key parameter will not update the cash or trigger revalidation unless there is a mounted hook using the same key so what that means is when we use mutate with a key it will go ahead and update and invalid revalidate all the active svr hooks that are mounted so because we are on this screen and it uh is rendering this one it's actually revalidating and updating um so yeah this is our Global uh mutate function where we have to specify the key that we want to refresh or update we don't even have to provide data here it will work like this as well if we run a mutation it will go ahead and revalidate and send the request again to the server mutate what's going on here yes it's sending a request again uh anyway another way we can run mutations is the bound mutate [Music] when being run it will refresh and update this key so basically it's a shortcut to the global one where we don't have to provide the key we bind it to the uh data fetching itself and if I'm going to go ahead and check the terminal to see what requests we're sending we're going to see we're going to see if I press mutate it basically refreshes and updates the the the post here so maybe the button should be refresh so when we call the mutate without any data it will simply trigger a revalidation it will Mark the data as expired and trigger a refetch so this can be used for example when we log out a user we are logging the user out and then we are calling mutate that function and it will simple trigger like a refetch to go ahead and fetch again the API user for remote mutations um we can use the use S SWR mutation this is when we want to send data to the server uh we are similar to the mutate that we saw previously but the only difference is that they will be triggered manually for example when we press on a button um this is the comparison to use S SWR let's see how we can do this kind of uh remote updates update user for that we're going to go into the probably posts because this Json also has for example post requests so let's see in the guide how we can send a post request creating a resource we need post Json stringified okay so let's call this fetch function and in fact uh the resources will not actually be updated on the server but it will be faked as if so let's go ahead and copy this fetch function and we're going to go into the posts in the posts here we're going to have like the definition of creating a post we have this fetch that we need to wrap it around a fetcher a custom function similar to this fetcher arguments update user it will have you it's a sync it will get URL and then arguments so so first things first we're going to create a function called uh create post which will receive a URL and then it will receive uh a the date about a post so new post as an argument now inside there we're going to put the fetch request we're going to make this function asynchronous and we're going to think we need to to do what to do const response equal a weight then I'm going to get rid of this van and so on and I'm going to Simply return response. Json now instead of this fetch I'm going to put the URL because this is going to be passed by the key there and the new post is going to come here instead of Json stringify so now this is a function that when being called with a URL and new post will send a request to our API with this information so now let's create a new hook probably called use create post that will have a following format it's going to be similar to this custom hook but in this case it's not going to have it's not going to use the us svr it's going to use asvr mutation where is it imported from okay it's imported from svr SL mutation use SV mutation we need here the key which is going to be the URL that we want to send the data tool so it's going to be this posts and then it will have data and the data uh I don't know the data yet probably we're going to H pass it through a trigger yes we just need to provide the update user or create post function here the most important thing is that it will give us a trigger which is a function that when being called will will trigger this mutation so let's export it from our custom hook and now we are ready to go ahead and call this use create hook probably in the post screen and I'm going to update the button for from refresh to or maybe we can create a new button with a title create post and the function that it will call is going to come from our custom hook called use create post are we exporting no we are not exporting it here so export const and here we're going to be able to import it together with a use post now use create post will give us the trigger function that we can call on create post a lot of functions but this will Define like a very clear structure and it will be quite scalable so in a moment I'm going to stop and explain again like what we are doing I understand that it might be a bit confusing because we're jumping from file to file we have a lot of functions hooks custom Hooks and so on but in a moment everything will make sense so um when we call this on create function that will be bound to the on press event here what we want to do is we want to trigger uh our mutation our use create post and send v a new post that we want to create the structure of a new post should have Title by and user ID so something like this title body and user ID Tes script is complaining a bit but we're going to we're going to fix it in a moment now let's give it a try to see if at least our post request is being sent correctly to the server if I'm going to press create post here we see that we are sending a post request yes it's a post request I'm not sure why I cannot zoom in oh with minus it works so I can do that okay so the good thing is that we have we see that we have the first request here post is to our SL posts and it correctly sent if we look in the payload the arguments is body title and user ID so that means that it correctly created it and it gave us back even by ID of a newly created post which is not going to be uh updated there but anyway it's uh it's a good thing to to see there is preview and the second request this is a get request because it invalidated the same URL so it knows that there is some data behind the scenes so let me go ahead and refetch the post from the server perfect uh um so let's review what we have at this moment with our mutation um what I will do actually is let me go ahead and inside our posts where we have here create post uh the new post will have let's create a type for it new post and let's give it here to properly type it uh the new post as we saw has a title body and user ID so title string body string and user ID number now if we look at the post screen will it understand this no it doesn't create post trigger should I do it like this yeah this is already about types script so let's see how we can Define the types for our uh how is it user e yeah uh not really sure how to provide properly here the types use S SWR mutation data so if I do if I specify that the data should be a new post or maybe it's going to be for now any than any then key is going to be string then extra arguments if extra arguments type is going to be new post will it understand come on key string fetcher oh what it's a it's a promise books okay I give up on uh on defining the types here I'm missing something um so don't worry it's it's going to still work it's the only disadvantage is now when calling the trigger it doesn't know it it expect this function but to um let's go ahead and uh review what we have done in order to send a mutation first of all we provided a function that will actually send the fetch request to the server uh this is a very normal function that knowing a URL and the information about the new post will send a post request to the URL using the new post as the body now we use this create post as the function that is being called by the use svr mutation the use svr mutation here we're providing the the URL which serves both as a key and also as the URL that is going to be sent to the create post here now we use as WR mutation in is very similar to the use aswr mutation the only thing is that it will not execute the mutation automatically it will give us a trigger function that we can go ahead and call it when something happens when for example the user presses a button so when we press the button we are going to call the trigger function with this information and back from this us svr mutation we can also have data we can also have have is mutating we can also have error and we can export all of these things here and instead of data maybe we can call it new post for example new post what way around new post is going to be equal to data now in our component we can go ahead and besides trigger we can also get the new post and whenever this happens we can go ahead and do a console log new post the new post is going to be the information that we receive back from the server and after I press create post do they have an error there something is going on reloading what's going on I'm going to stop the server start it again come on okay and let's open it again now if I press uh initially it's undefined because we didn't run the the mutation yet but after I press create post it's going to have have the body title and the new ID uh of that post perfect so let's see what other possibilities do we have using mutations uh use svr mutation optimistic data is actually very good concept let's see so yeah we can um provide optimistic data which will optimistically update our UI without waiting for the response from the server that's very powerful to make our UI even feel more faster to do that that we can provide this as an option either to the uh use svr itself or we can do that when calling the trigger so here we can provide optimistic data which is a function with current data um and we should do something with current data let's start by returning return current data and let's do console log optimistic update and let's do console log here for the current data and let's see what we have here so if I'm going to press create post we're going to see that this is the whole current data so optimistic update it is an array with all all the posts currently in our list why because this trigger function is sharing the same key as our request for getting the posts so that basically means that we are sharing the same cash for the posts because if I'm going to use I don't know posts one to three in this case you'll see that by pressing create post we see optimistic update undefined because there is nothing in Cache for this key that's why when we using the same key for post and for for getting the posts for creating a post and for fetching the posts we are going to be able to um hook into the same cache and update the data Veer without waiting for a response from the server to do that what we can do is on create post let's do here const new post is equal to this object I'm going to send the new post here the new post as the first parameter and what I'm going to do is in the optimistic data I'm going to say that I want the new post to be the first one and only then to put the rest of the current posts this way I want the new post to be on the top right after pressing the button without even waiting for the server to give us a new response so if I do create post we will see that initially for a for a split of a second we see a new post there uh and if you change the user ID to two you're going to see that it also changes the name but because our trigger function also inside the option revalidates after success it goes back to the normal one because we are actually not saving this on the server we are only simulating this so what I can do is revalidate and then if I do false I think it will not revalidate the request and after pressing create post we are optimistically updating it on the UI and because we are not revalidating the cache it stays here and I can create a new one and I can create a new one and they instantly appear here so this is how you can do optimistic updates using svr and it's documented more here under optimistic updates in many cases applying local mutation to data is good way to make changes feel faster no need to wait for the remote source of data with optimistic data option you can update your local data manually while waiting for remote uh mutation to finish composing roll back on error you can also control when to roll back with data if something didn't go as expected so for example what if we are optimistically updating our UI but then the server sent us back an error saying that I don't know you made a mistake let's simulate that by going into the posts and in this create post I'm going to change something I don't know I'm going to comment out the body and this means that without a body most probably the request will fail to double check that I'm going to open the network debugger I'm going to clear everything here I'm going to reload to make sure that it's connected I'm going to reload again it doesn't seem to to be connected so I'm going to close it because we restarted the application I'm going to press J one more time to open the debugger I'm going to go to network and here let's go ahead and refresh our application come on sometimes it needs a couple of refresh until we see the requests but let's see what happens if I press create post it will send a request to the PO SL poost if I see preview it actually worked so it didn't even without a body it worked uh maybe method should be post one two three will it fail in that scenario create post payload preview response I believe it failed but we can check that we can check that by going ahead and and doing what in the use create post it will also get give us back the error and if the error happens or maybe we can actually do it right here when we call trigger let's call it using a weight and put it inside a try catch catch let's console log the error let's see if I'm going to see the error here create post Yes Network request failed so what I'm going to do instead of console log here I'm going to use an alert alert dott failed to to create the post this alert can be imported from react native so now if something goes wrong with a server we see fail to create the post but the problem is that oh it automatically it automatically does that so as you can see like for a split second our optimistic data is being shown but if the request failed the optim optimistic data is being rolled back because yes we optimistically added it to the user interface but in fact there was something wrong on the server it didn't manage to create it so it's better to roll back to to uh get it get it out of our user interface and we can also um we can also um configure when we want to roll back by providing here in the options and roll back on error which is a function that will receive the error and depending on the type of the error you can go ahead and return true or false if you want to roll back or not so if I return false meaning that I don't want to roll back if error happens uh you're going to see that even though we see the fail to create post though the cache is going to remain with optimistic data which is not very good but in some cases you might want to do that you might also want to display here retry or something like that anyway like locally in the cash Bas data exists but it failed to be updated on the server and we can adjust like the behavior of svr and how it will manage the cache using a roll back on error in this documentation it shows uh it shows that um roll back only if the error is something else than abort error roll back yes only if it's not a board error if it's a board error keep it there not sure like where you would use that but anyway that's good to know that you can adjust that based on the error that it receives and I'm going to go back here and change the request to actually work and now everything is working perfectly fine yeah very powerful I hope it's not too confusing let me know in the comments how do you how do you see it so far and if you press refresh this is our basic mutate that will uh update the use post so it gets back to the initial State all right so that was our optimistic update when you have optimistic data set it's possible that the optimistic data gets displayed to the user but the remote mutation fail in this case you can leverage roll back on error to revert the local cache to the previous state to make sure that the user is seeing the correct data let me go ahead and commit and also you can update cache like even for something else when something happens for example sometimes the remote mutation requests directly Returns the updated data so there is no need to do an extra fetch to load it you can enable the populate cache option to update the cach for uses VR with the response of mutation so yeah in some cases we can manually populate the cach like after an update for example after updating something we can update the cache and stop the revalidation to save some extra uh request to the server okay so that was most of the things that I wanted to show about mutation in the documentation you can find out more information about that if something is still unclear I recommend going ahead and playing with this trying different things trying different scenarios use cases and implementing them um this information with use as aswr um error handling yeah we can also specify how when do we want to retry requests for example if the status code is 404 which means not found we don't want to retry that requests uh in other cases we want to retry not more than 10 times or after 5 Seconds we can also do that as well oh and here is the information about how you can globally catch errors and report them with your re reporting tool like Sentry or you can show a notification on the UI uh what I also want to show um there are two important things that I still want to to show here I want to show how we can fetch graphql apis and then I want to show some very specific react native configuration that we have to take in order to to to make most out of use S SWR because on the web use S SWR can hook into some um states of the of a website like whenever the tuab gets focused or whenever we navigate to a page then use aswr will revalidate the cache for mobile we need to take some uh steps to provide this information like when should this re revalidation happened when the network connectivity became available so that for example if we go from no network to having network use awr um will make sure to refetch everything for that we need to take some extra steps and we're going to do that by the end of this video but first I want to show you how we can fetch graphql apis as well uh for the graphql API I think I'm going to go ahead and create a simple graph API using stabs and so let's go ahead on steps then and let's go ahead in the build graphql or maybe in the getting started from developers I'm going to go to the documentation actually so here in the documentation uh let's go ahead in the install and setup and follow these steps if you don't have steps and CLI installed on your machine all you have to do is install stepen globally uh stepen is going to help us configure and create a graph API in a couple of steps like very very easily so we can test it in our application for that we need to First make sure to install stabs and CLI globally then make sure to create an account you can also use the link in the description below uh you can create a free account and on the account page you're going to find your admin key and the API key take note of of that those keys because in the next step we need to log in with our stepen CLI to do that go ahead and run stepen login and here you're going to be asked to provide your account name that you can get also from uh let me try to log to my stepen account give me just one second so from your dashboard go to the Keys and you're going to have account name here provide it in the terminal then provide the admin key the admin key that you can take from here press enter and after that you should be successfully logged in to staben now what I'm going to do is I'm going to create a new folder called staben in my project where we will keep the configuration for staben now in my terminal let's go ahead and do a CD stepen to go into that directory and we can make sure that we are there using the PFD like to see the puff yes we are in the steps and directory now that we are here with a simple command line command uh in the CLI we're going to be able to trans transform a rest API into a graphql API let's go to this documentation on how we can transform rest API to graphql API and all we have to do is using the steps and import command and then follow by the coral request we're going to be able to send a request and um create our graphical API so first let's try to Define this SC request um and make sure it works for that I'm going to go to the Json placeholder and I'm going to take the URL or in fact I'm going to go to the source hooks posts and let's go ahead and take this URL because this is a get this is an endpoint that we can send our get request and it will give us a list of posts to validate that I'm going to open back the terminal and I'm going to do curl and then provide this URL oh come on let's do clear let's do curl and then provide this URL if I paste it we should see an array of data so that means that our Cur command is working successfully now all we have to do is to this to this scroll command we need to prefix it with stepen import and that's it stepen now will ask us about what name we should give our API I'm going to go with a default one stepen we'll send a request to this API will introspect will analyze the response and will build our API our graphql API now all we have to do is run steps and start this will go ahead and deploy our API to our uh steps an account and here at the end we see explore it with graphical so if I'm going to open this URL in browser we will see our graphql API if I send this we see the title The Body the ID the user ID uh and the query that is being sent the nice thing about this graph this is that it's a graphical API so we can really select only the things like the title uh of the post and that's what it's going to return so that's all it took for graphql for steps and to set up and configure this graphql API by simply importing an existing rest API now what I want to do is I want to send requests to fetch this graph API using uh s SWR let's go ahead and see how we can do that by going to to the getting started I think here we have a URL to yeah if you want to use graphql API we can check here which is data fetching oxio and yeah under the data fetching we can see see how we can fetch graphql apis um for that we're going to use a library called graphql request so let's go ahead and install it in our project go ahead and open a new terminal and make sure that you are in the root directory of your project not in size tabsen now we're going to install the graphql D request which is a library that will help us send graphql requests now here uh we are going to define a fetcher a graphql fetcher request graphql and then query let's take this fetcher and let's use it in the utils under the fetcher let's export but rename this to the gql fetcher and this will make sure that it's a graphql fetcher it depends on the request that was being imported from graphql request and this is the URL that we will send a request to where do we find this URL well this URL we're going to find in the page where you did steps and start if you lost the terminal where you you you had steps and start you can open a new terminal navigate to steps and directory and run again steps and start this will redeploy if there are any changes and then it will show us basically this call request Vis SC request contains this HTTP URL that represents the endp point to which we should send the graphql requests let's copy it let's paste it here it should have your account name it should have a name of your API and vanore graphql uh but there is one more thing it needs a header for the API key how are we going to provide this header here I think it's the third parameter or no let's check the graphql request documentation to see how we can add headers graph graph qu request request document variables and then request headers so it's the third request well in this case uh the request should become an object where this is the URL this is the document the query that we will receive and we will provide request headers and one of the request headers that is important is the authorization which should have the string API key and then our actual API key which we can get from our steps and dashboard here under API key I hope that's correct and we're going to test it in a second authorization a key and then the actual API key for us for us now that we have this helper function to send a graph Co request we can use it inside a inside the use S SWR uh hook for that let's go ahead in our application post screen let's try let's duplicate this post screen and call it graphql post screen I'm going to rename it also to graph ql post screen and I'm going to remove some of the stuff from here I'm going to remove the new post motation the Run motation basically I'm going to remove these two buttons and leave only the flat list not going to cover the mutation I want only a graphql request that means that on create post we no longer need this function so I can remove it completely and run mutation we no longer need it just like that so now graphql is a very simple page but in order to see it in action in our up. TSX it was automatically updated but yeah from up. TS we are going to import both of them so we will be able to change which one we are rendering I'm going to use the use S SWR that we are going to import from use S SWR from s SWR here we need a query document const query equal is going to be a string and we need that document the graphql query that we want to send the query itself we can take it from the graphical dashboard from steps and dashboard where we created it here so let's select the title and the body and this is going to become the query that we want to send I'm going to copy this query and I'm going to put it in our query document here now let's take this query and send it to use aswr and as a fetcher we're going to use the graph or gql fetcher that we defined previously uh now it's not going to receive post but data so let's take data here and hopefully it's going to have data but not only data but data dot my query I believe is going to be the URL yes because if I console log data or even if we look here we're going to see if the data contain contains a key called my query which is the array that we need so just like that we are sending the graph request and I'm going to show you that it actually works by simply removing the body from this query and if I save it's only going to contain the titles and vice versa if I add body here but remove title it's only going to have the bodies so this is how we can send graphql request as well basically use S VR is um back and agnostic fetching Library meaning that all it needs is an asynchronous function that will either throw an error or will return some data that's everything used asvr needs now it's our job to provide the the fetcher like how we want to get the data for a restic API we can use the fetch library or axos and for graphql request we can use the graphql request library that will send this request to the to them to our graphql API so just like that we also saw how we can do graphical requests and I think it's good if we if we add them I'm going to take I'm going to if we extract from graphql post here if we extract the logic of fetching also to a separate hook inside posts I can duplicate our use posts and I can name it use graphql posts and this is going to need a query that we Define here I can maybe or yeah let's do it like this I'm going to take the query I'm going to pass here to the use aw use s w r and instead of a default fetcher I'm going to provide here the gql fetcher that we defined and everything else will be like this only the posts will be taken not from data but from data dot in the name of my query and I'm going to safely access it because it might not be defined now we can use this use gql Post in our component and we can remove a query itself and the fetcher and only import this hook and everything is going to be much simpler here instead of data it's going to be be posts so we can take posts and render it right away in the flat list so posts right so from the outside of our custom hook the API Remains the Same being it uh whether is taken from graphql or rest API the API is the same so by doing these reusable hooks we can switch things around without having for us to update our components our screens the API is going to be the same we can only change like where it takes it from do you want it from graphql or do you want to take it from for example use posts like this it's going to have the same effect and as you can see with use post it renders the user but with use graph post it doesn't render the user that's because in our query that we are sending to graphql we didn't include the user ID if we do include it it's going to have the users as well so just like that we have also graphql posts as well let me go ahead and do a git status G add git commit dql requests with svr perfect so that is the graph part the last part that I promise to to show is specifically around react native svr is actually made for react um but it's as you can saw it's compatible with r native as well however there are some small differences and let's open the advanced react native guide and read about these differences uh the thing is that react applications are running inside the browsers while re native has a very different user experience for example there is no tab Focus switching from the background to the app is considered as a focus instead yeah like the experiences on the browser like when things should re be refreshed is very different to The Experience on the mobile and in order to customize these behaviors we can replace the default functionalities of a focus and online State online event listeners with a specific event listeners for re native and then configure asvr to use them let's see an example where what we're trying to accomplish here is the way svr works for example if we would Implement svr on a web page whenever we switch tuab and get to that page svr will automatically detect that event and will revalidate the data to update with new fresh data from the server on the mobile phone we do not have this kind of tab changes we actually do have if we are using like a navigator like a bottom tab Navigator or a top tab Navigator and that's actually a very valid point however on mobile another thing is if application goes from the background if we open it back we want to revalidate this data at the moment if I'm going to open the debugger we're going to see that this is actually not happening let me reload uh we see everything here if I close it uh clean it and move application in the background State and bring it back in the foreground State we see that no request has been sent which means that we are going to see like old data we in a perfect situ scenario when this is happening when the application comes into the foreground we want to tell svr hey go ahead and revalidate this data because there might be changes from the time it was last loaded so svr doesn't support this out of a box but it allows us to configure it manually for the platform specific events so that's what we're going to try to do first of all we're going to use the global configuration to make sure that this configuration is used everywhere what we're going to do is we're going to customize the focus and the reconnect events there is a few configuration you need to take care of such as is online is visible in it focus and in it reconnect is online and is visible are functions that return a Boolean to determine if application is active by default svr will bail out of rev validation if this conditions are not met meaning if there is if we are not online svr will not even try to revalidate so these are the two things that we can go ahead and Implement in our svr configuration let's go here and under in app. TSX under svr config we can provide this configuration as separate function is online we need to do something and return true or false if a device is online the same thing with is visible for now we're going to always consider them online and visible then there are two other methods init focus and init reconnect let's also add them here and let's see what are they used for the init Focus will register The Listener with your state provid Ider uh yeah let's yeah when using init focus and init reconnect it required to also set up a custom cach provider you can use an empty map or any storage you prefer um so that means that we also need to provide a to create a provider so at the top before is online we're going to create a provider as a custom map we're going to see later if we can use like other providers but for now the map should work so let's take the init Focus as an example in it Focus uh what it it will do here is using the UP State from react native it will take the current state and it will also subscribe to Upstate updates whenever this happens we're going to other use um call this callback function so that as we are starts initializing the focus event and starts revalidating the queries that it needs to revalidate and let's let's actually take it a code from here in our init for focus in it Focus basically we need to um call this call back function whenever a screen regains Focus so using the UP State from react native what we are doing here we are taking the current up state yeah we're taking the current up State and we are subscribing we are adding an event listener to the upstate whenever it changes we're calling this function that we Define here so what it does it it checks if the current up state is inactive or background and the next up state is active only then we call back basically if we're coming from inactive or background into the active State we want to call this function to initialize the focus so let's reload and see what's going on here uh let's do a console log here changed from background to active and then we can also do console log State up State and let's console log the next up state I'm going to open the terminal to see this things actions so if I'm going to do like that we see that our up State changed to inactive if I go like this it should probably be still inactive if I go back and after a couple of time it goes into the background and then when you press on this it goes from background to active and our if statement checks if it's coming from background or if it's coming from inactive to active we are calling this change from background to active we are calling this call back function and in fact when this happens I expect our data to be revalidated we can check that with our our Network console let's reload our application again until we see some requests yes now we see them I will clear them out I'm going to move application in background and now when I bring it back in foreground I expect a new request to be sent to the server will it yes it reinitializes the focus and it sends the request to revalidate the cach to make sure that we have a latest data here to see that in action we can go ahead in up. TSX and instead of graphql post screen let's render a post screen because this screen will allow us to create some posts like this and it has some posts which are only local and if I go into the background and then come back it will very soon refresh and I'm not sure why it still kept this to weird but if I create one post go to background and then come back here it will revalidate to make sure that the data is most up to date from the server perfect so that was the init Focus for init connect it requires a thirdparty library such as net info to subscribe to network status uh updates the implementation will be similar to the example above receiving a callback function and triggering it when the network recovers from offline so svr can start revalidating to keep your data up to date so let's try to implement that ourself Expo net info net info is um is a library that allows us to subscribe to network updates when we go from offline to online mode Let's go ahead and install this react native Community slet info in our application and see how we can subscribe to that here is the Subscribe and unsubcribe I'm going to put it here in the init connect and let's figure out what we have else to do we need to import net INF for at the top of course in need connect um then we're going to to in a similar way keep the network state in a variable so let's do let Network State equal to instead of event listener I'm going to Simply take Network fetch can this be a sync I hope so it cannot let's check the documentation [Music] is is connected is internet reachable details well I'm going to do Network state or network available let's initialize it with false aaable network available is false now we're going to take state is connected and we're going to do an if statement here if network is currently not available and the state and it updates to State DOT is connect Ed then we're going to call the call back and we want to update network available with a previous value with state is connected and then to unsubscribe I think we actually have to do a return here so we need looking at the top we need to return return a function that will called unsubscribe yeah I hope it will work let's do a console log Network update and then let's do state DOT is connected and here reconnected now what do we have to do Network updated through reconnected good uh then we need to go into no network can I do that where can I do that through features how can I turn over them I'm pretty sure that is not possible if I do here offline and then fast don't think that is going to work iOS simulator turn off WiFi so there is no way to disable network on iOS simulator that's the solution my God I would need the network link conditioner maybe what I should do is use my physical device I think that's the best way so let me go ahead and and scan this QR code my storage is full nice come on come on loading okay so these are the logs from my actual device uh we see that Network updated to true now if I'm going to go ahead and turn off the network I don't see anything here because it stopped sending data oh boy but anyway I see that it's working on my physical device so when I when I reconnect to the network it automatically fetches new data from the uh from the server and that's how you can provide this um customization that will um revalidate our s SWR cache when our application regains Focus or when it regains connectivity but this is I would say a very let's actually maybe go ahead and extract this aswr config to a separate file because it contains a lot of things should we maybe let's go ahead and here in utils let's go and create a new file s SWR config dots or configuration. TS and let's copy the whole value from here because it's a lot actually and Export it here as an object export or maybe first Define config equal to this and Export con config let's call it aswr configuration it needs the fetcher to be imported it needs the UP State from react native it needs net info from this one I want to make sure that you have a starting point that you can use in your project and not not have everything there and here in the configuration let's use S WRR configuration imported from our utils now I can clear a bit this stuff and it still works yeah perfect uh what I wanted to say before and actually let me go ahead and do a git OD git commit Focus um revalidate on up focus and where on network reconnect what I wanted to say is this is a very uh let's say basic configuration for the focus events for connection I think it's pretty stable because Network requests network connectivity is quite straightforward but the focus event is quite tricky because if we are using for example a tab navigation we might also want to trigger a focus event when we're going from a tab to another one same thing with a bottom tab navigation so as you can see there are more use cases where a screen should trigger this Focus event to revalidate data on that screen and you can implement this yourself uh or actually preparing this video I stemble upon upon the library made by Fernando Rojo that is specific configuration for svr for R native shout out to Fernando Rojo for doing a lot of uh support for the r native community building a lot of useful libraries but that basically is a re native uh it's a compatibility layer for the use S SWR hook that supports react native and react navigation what you should do is simply install this library and replace the use aswr to use S SWR native everything will remain the same but now um the revalidate on focus revalidate on connect will work out of a box for the rec native environment so it's a simple dropin replacement for use aswr for react native I haven't tested it yet but I think it's pretty straightforward and the value is there like we don't have to with that Library we don't have to manually manage like this connectivity States it simply add supports for revalidate on connect revalidate on Focus and that's it simply add install the [Music] library and replace use S SWR with s SWR native that's it give it a try and see how it works anyway uh that was everything about s SWR to be honest uh this is the first time I've used s SWR in rck Native um in Jan mineral actually and it's actually pretty good it's very simple uh it doesn't have a lot of Concepts to to get your hand around so after understanding like how this cash is working and using like proper Keys you can really build a very um fast and interactive application with optimistic updates with data invalidation revalidation when things are happening and I think yeah it's it's it's quite good most probably I will use it in more applications in future and let me know if you enjoyed this tutorial let me know your questions down in the description and if you enjoyed it make sure to subscribe to the channel That helps us a lot to provide more and better tutorials for you guys and also this Friday in two days we're going to do a new tutorial we're going to rebuild the Apple wallet application with very nice animations for scrolling through the cards so if you're interested make sure to subscribe turn on the notification Bell not to miss it out and I'm going to see you next time bye-bye
Info
Channel: notJust․dev
Views: 4,456
Rating: undefined out of 5
Keywords: vadim savin, not just development, notjust.dev, react native tutorial, react native for beginners, step-by-step tutorial, SWR, data fetching, caching strategies, real-time data, react hooks, SWR setup, error handling react native, data fetching in react, data caching in react native, swr in react native, React Hooks for Data Fetching, how to fetch data, swr tutorial, fetch data in react, react swr, swr react hooks, useswr, swr preload, data revalidation, swr optimistic ui
Id: lleZC3gyZYU
Channel Id: undefined
Length: 164min 9sec (9849 seconds)
Published: Thu Mar 28 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.