Connecting Twitter's Frontend to Backend using node.js and React Native

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's up node.js developers welcome back to a new live stream and today today what we're gonna do is we're gonna connect the front end of Twitter that we have built in the previous episode you with the back end that we have also built in the previous episode so we're gonna put them together from react native we're going to query our rest API that we have built using react query and also we're going to implement the authentication I have authentication screens in order to allow users to create an account and to sign in to use the application so let's quickly the plan for today if you haven't checked out the previous episodes I will leave a link in the description there are two very value-packed episodes in the first one we have built the Twitter the Twitter UI in rack native using rack native expo Expo router and here is the result of our first um our first episode I'll also provide the source code so if you haven't checked it out like I will give you the um the code to be able to follow along From This Moment so yeah this is what we have at the moment we will also be able to create with uh post there go back and so on so this is our front end and the code for it you can find in the description below we're going to GitHub not just Dash Dev slash Twitter here is our application I'll make sure to create a UI branch that will include only the code that we have at the moment so if you're watching it afterwards make sure that you're checking the UI Branch actually let me do it quickly right now so git check out minus B UI and git push origin UI and now all the code that we have at the moment is going to be in the UI Branch here perfect the second part in the second episode what we did was to create our API that will allow us to manage our users manage our tweets and also will authenticate users using passwordless authentication this is a big part of a previous episode so if you're interested in that if you're interested how you can Implement yourself authentication without passwords only with emails and with one-time passwords that users receive on their email then definitely check out the previous episode where we do that on the back end we integrate we create all the tokens we send this email to the user and today we're gonna connect it with our front end so uh again via the back end the back end is going you will be able to find the backend also in our GitHub account and it's called Twitter backend just pull this Repository and make sure to install the dependencies using npm install and after that we can do npm run Dev we need to run the development server to start receiving requests and we see the server is ready and we I think also are ready to to get started should I just zoom in a bit so you can see better yeah I'm using also this extension that someone recommending recommended me were previous episode for a Founder client that allows me to create these requests and test our API so here are a couple of endpoints that we're gonna have to interact from our rec native application today and for example here like if we look at the login everything is going to start with this request we're gonna send we're going to receive okay and we're gonna receive an email on our account on our email with a code that we can provide here to the email token and after that we would be able to do the rest of our queries like list tweets and so on so that's quickly the plan uh as well today as I said we're gonna learn about react query this is something that I also started using recently and I really enjoy working with query let's see how it will play in our rec native application today um and hello everyone in the chat how are you doing guys how are you ready have you finished the previous episodes let me know hello from Tunisia hello Ahmed hello Atlanta India by the way guys if you're enjoying our project-based builds make sure to subscribe to the channel and be part of the one percent because from our analytics let me find that analytics to show you from our Analytics here we have it 98.5 percent of people are not subscribed 92.5 percent of people watching this live stream are not subscribed so please if you're enjoying what you're seeing here if you're taking some value if you're learning something new make sure to subscribe to the channel and write in the comments like I'm part of one percent and we will know that you you're supporting us and making sure to to help us reach more Developers hey Momo thank you very much for the donation so where do we start let's start uh not from both indication but let's actually start with some uh queries and the most important query in our application here is this list tweet query that will give us all the tweets so um if I go to the back end the list with query is this one and if I would try to send a request right now we get an error back with our API token is expired so we would have to generate a new API token and how do we do that we do that by following the login flow so firstly we uh send a login request then on our email we should receive the token the email token which we can provide to the authenticate here so let me quickly check the email token or actually I'm also uh where is it yeah if I open the logs here is the email token but I'm console logging but I also receive it on email so if I do send right now we get back an authentication token that we can sign over future requests like list tweets so going back to the list tweet we can go into the authentication here and we can replace the authentication token like this and if I send right now as you can see we get back an array of tweets so this is exactly what we're gonna have to do from our rack native application um on our feed screen and before I get into that I'll quickly show you how to fix this issue with uh where the first screen says that it doesn't exist and we have to go back to the feed uh I was I was trying to fix this issue in the previous live stream for quite a bit but the fix is very straightforward actually so what our application is missing is their home screen the home screen basically is should be the index.tsx file inside our application folder this is because we are using Expo router and the home page should be the index.tsx so it should be there but the problem is that we want our home screen to be the feed so the feed is inside drawer tabs feed and here index so that's why I was not creating this index because I wanted our feed to be home screen not some other home some other page but actually what we can do here is we can export default I don't know index the component and here inside the component we can simply do a redirect using a component redirect from Expo router to that href that we need so based rabbit we need is um drawer is inside of a parenthesis so it doesn't it's not part of href tabs is not part of href feed so slash feed and we need feed index so we're gonna stop here uh what's going on here export default function index and redirect to feed now if I'm gonna refresh the page it's going to go to the index but the index will redirect to the feed and this index should always be here because if we are sending um a deep link to the root of our application we should somehow handle it so that's why we need the index that will redirect to the feed perfect so I can even do git add like this okay so now going back in our application folder this is where all our screens from replication leave let's go to the drawer tabs feed and here in the index is where we have our flat list with tweet and do a moment these tweets are coming from dummy datum but what we want to do is we actually want to get these tweets from our API hmm let's see let's see yeah as usual I will try to do everything like in this screen to not confuse you with a lot of files and then we're gonna start extracting logic in different files to separate concern concerns and to keep everything clean so where do we start from first of all because we have um because we will query our API the result is going to be stored back into a state variable so all the tweets that we have here imported from the assets instead of being there we're going to define a state variable for tweets and set tweets which is equal to use State and an empty array now we can go ahead and comment out the import from the dummy data and our home feed should be empty because now the tweets are an empty array okay the next step is where when do we want to query our API we want to query the API as soon as this screen which is tab one screen but probably it's better to rename it as feed screen as soon as this feed screen component mounts so for that we need a use effect like this use effect with an empty array as a dependency array to make sure that this use effect only is being called once when we Mount the component so what do we need to do here well we're going to have a function fetch tweets which is going to be an async function in this fetch tweets we are going to have to actually fetch the tweet and let's make sure that we are calling this function right away okay perfect now we have to send an HTTP request in a similar way as how we did here with a funder client to our server at the moment our server is running at localhost 3000 so make sure that it is running in you can send this request from your founder client and now our next step is to actually send a request to this URL so let's get this URL come back in our react native and fetch tweets from basically this localhost how do we do that there are a couple of ways to fetch uh and rest API basically to send HTTP requests some of them are using external libraries like actuos but there is a a method that doesn't require us to install any third-party libraries and is part of them is pre-built so we have access to it and here I'm talking about the fetch API so this fetch API allows us to send HTTP requests where let's do const URL equal let's call this put this URL that we want to fetch here and let's do URL here now what we can do is we can get the result by awaiting this fetch request let's go ahead and do console log result to see what we get back now if I'm going to open the terminal to find vower Metro bundler somewhere in these results we see this log and if we look throughout this log we see status 401 status 401 is for a requests that are not authorized so what does it mean it means that we sent a basically we're not of rights to access via API because we haven't provided the authorization key how do we provide authorization key we can do that by providing a header so if we send to the fetch API extra options here we can pass here some headers and some of the headers that we are interested in and if we look at our API in the middlewares of middleware we see that we are depend on the authorization header so let's take this authorization header I think we need to capitalize it and here in the authorization header we need to send them actually let's send the template string because the authorization header will contain the word Bearer and then the token the authentication token at the moment we don't have authentication token here in the application manage automatically we're going to do that when we Implement authentication but let's as well store it into a variable hardcore hard-coded from our API here where are we authenticated or you can look even in the database for an authentication token but I'm going to take it from here from the previously from them last request we made to the authenticate endpoint and if we put this authentication token here now let's open up here and try to reload our application to see if we still have this error no we don't and I see that the status code at the moment is 200. so right away as you can see we can Define we can do some error Handler handling based on this status code so we can do if response dot status is different than 200 then let's do I don't know we can alert or do some actions but actually I don't really care that much here because we're gonna change the place for this and it's gonna be a bit different error fetching the API but how do we get access to the actual beta of a tweet these tweets well we do that by accessing the response dot Json response.json and this is where we're gonna get our tweet so what we can do is we can right away set in our state but tweets as response Dot Json we need to call this function and if I refresh nothing is happening because uh response.json let's have a look at the console log here possible typer already read already oh because we have two of them so let's do it like this const data equal response.json let's console log the data here and let's set it in state and we see that when we see an error like this it usually means that we forgot to await a promise and this response.json is a promise so we need to make sure to await so because of that it didn't show up but now as we can see we have our first tweet from our database in our feed and to show that it's actually coming from the database we can go to the back end and we can run npx Prisma studio and that will open Prisma studio for us to to explore our database so if I'm gonna bring it here in the Tweet we see all of these six tweets that we see in there on the screen here they match our database foreign just wanted to ask is your programming course in typescript um the full Stack mobile development course we have their projects that are using JavaScript and they are targeted at beginners that are just getting started with Rec native but as we gain more experience the main project of a course is actually using typescript and they are like you teach you learn everything you learn to build full Stack mobile applications using typescript so the answer is both typescript and JavaScript and if you're interested to learn more about mobile development and if you are serious about becoming a full Stack mobile developer developer make sure to check out our premium course Link in the description where you can go at academy.nojust.dev yes thank you for the question hello from Sri Lanka hello okay so uh let's go ahead and here I think code is too huge like I cannot fit it on the screen so what I want you to do now is always fetching logic is low level logic of interacting with the API so it's kind of not recommended to keep querying logic and specifically this low-level logic of dealing with off tokens with the headers and so on to keep it together with your high level components that are simply rendering flat list of tweets that are responsible for the UI so what I want to do is I want to separate the querying logic into some separate files and for that let's go ahead and create a new folder let's create a new folder lib where we will keep all our internal libraries and inside the lib I can create a folder API where we will keep all our API interactions files in this API let's go ahead and create the tweets dot TS and here is where we will store functions that will do API requests so the function that we want to do first let's export it from here like list tweets it's an async function and everything here like the logic one should logic B we already defined the logic so it's it should be something like this like the flash tweet so let's copy most of the things from here basically the body of this function from here and bring them to our new library file like this uh we're not done yet because we are still some things we have to to change for example here instead of set tweets what we want to do is we want to return this data so let's delete this from here and let's simply return it here return also instead of console logging here I would uh I would rubber yeah I would rather throw a new error here but we're gonna need that a bit later so I'm gonna explain why pro new error and here Arrow fetching let's be a bit more specific fetching tweet like this now back in our feed what we can do here is let's import the list tweets function from the library API tweet and inside our first tweets function let's go ahead and cost response equal list tweets we need to avoid of course and after we get that result we can set it in state set tweets as response so now if I refresh everything should still be working like this but now in our feed screen we don't have low level logic of how our Israel fetching happening we only are calling that function still this is not perfect we're gonna get there um step by step but I want to go back here to twist.ts and make sure that we still extract some other things from here for example the URL that we will that we will fetch I will extract it from outside of this function as the API URL and I'm not gonna put all the URL but only the the main part of a URL so this part of a URL now the URL that I want because this part is going to be reused and it's going to be the same for all the requests so I don't want to repeat over and over again and moreover this part of a URL is the part that most probably will change depending on where you host the API but everything that is after this is not going to change no matter in what environment you are running your API being it locally with localhost or hosted somewhere so that's why I extractive API URL outside and now for the URL itself I can probably I don't even need it here I will go ahead and compose it inside the fetch function with a template string here because the first part should be the API URL then we have slash tweet or slash tweet the authentication token I can extract it right now as well we might we will change how this works later but for now let's keep it here yes and here I can remove this comment and the function is much more uh it's cleaner in now yeah I think one more extra step is to extract this API URL to a configuration file because again it's not to be only going to be used in this file but in other API files as well so I don't know you can have in the API config.ts that will contain API configuration and let's move both of these variables here and add export in front of them export like this now back in our tweets we can go ahead and import API URL and of token from config now it's going to be even easier when we add more files because we're if we want to change the API or authentication token we're gonna have to change it only in one place all right so with our fetching logic we are complete video how to host this local server if you are interested in how to host I was thinking about a separate video in this series where I can show you how to host this server in the cloud using AWS on an ec2 instance and also how to use an Cloud database that is going to be a postgres SQL database so if you're interested in this part of the back end of deploying and actually making it available um in production then let me know in the comments and probably we're gonna do it in the following weeks the next two weeks I'm not going to be home I'm traveling to Krakow to Abdu Jazz conference so if you're a beginner let me know I would love to meet our community but when I get back we can get back and do the deployment okay so um our next step let's go back in our um screen in the feed screen index here and see how we are doing the logic of calling this fetch function and other important stuff here the moment um doing it this way it's still not a huge problem but if you would like to add some basic functionalities that you'd expect from any application like displaying a loading State when we are fetching the tweets or displaying the error when um something happens we're refetching the same query were managing the pagination or managing or caching the result in order to not send this request over and over if we already have his data so if you would have to implement that yourself you would quickly understand how complex this part is of managing a remote data in your application so in a lot of cases developers are creating their own pseudo libraries for for for doing that or the alternative is to use an existing library that is specifically designed for that for this project what we're gonna use is react query so let's open it up we're gonna need to work with the documentation today because it's something new for me as well so Rec query is as we can see is a powerful State Management library for react application and specifically State Management that handles remote data from the server uh it's yeah I think it's going to make more sense uh as we get our hands dirty and start using it so let's go ahead in the documentation in the installation guide and I'm gonna go with a version 4 actually instead of version three version 5 is still in Alpha so I'm Gonna Keep it with version 4. let's start by installing a racked query library in our application so in our rec native application I'm going to run npmi 10 stack slash react query and after that is done what we have to do is we have to wrap our application with a react query client if you are familiar with Rec native like before react router you might expect something like a up.js or app.jsx that would be like the root file the entry point of our application and that's where we have all our context providers in Expo router the root the entry point or the root part of our application is managed by the root layout sorry by the file underscore layout from the application directory if we open it up here is where we can as you as you can see here is where we can do like theme providers where our client providers that we have to make available to the whole of our application to every single screen in our application so what we have to do here let's go ahead and import the client provider so let me query client so we have to import from tan stack racked query the client query client and query client provider this one so the first step is to create the client so client equal query client it should be new so client equal to new query client and if we scroll down until we go to the root layout navigation what we have to do is we have to wrap all of these components inside our query client provider let's close it add and here and we have to provide here the client that we created at the top so client client okay now we have access to our react query client in all our screens we can close out we can close this layout file and go back to our feed component from the App Drawer tabs feed index here instead of managing everything ourselves like a state like use effect and so on I'm gonna comment it out to have it to still have it on here on the screen but what we're gonna do is we are gonna use a hook called use Query from react query library that allows us to run queries use Query from times the correct query so let's go ahead and see how to work with a use Query hook this query accepts a expect some options and with two important options here is the key which is query key and this query key is an array of strings let's call this tweet and in a moment I'm going to explain what this query key is and the second part is a function is query function query FN the query fan should be then asynchronous function that we want to call in order to query our backend the specific particular thing about react query is that it is agnostic of what backend you're using so it that it really doesn't care like how you're querying your backend as long as you're providing an async function that will return data so we will ready that we already have a testing function which is called list tweets from our uh library that is doing this fetch fetching of our API so that this should be our query function list tweets from our Library API tweets okay back from news query we get first of all data and this data we can send to the flat list like this and just like that we replaced all of this code with a couple of lines of code to query our API but it doesn't stop here we've used query all of them features that I was talking about before like error handling as loading States retry refresh and so on this is handled automatically by the react query so the only thing that we can do we should do is to get this for example is loading from the use Query and in our UI say like if our query is still loading let's go ahead and return an activity indicator to make sure that we are showing some visual feedback to the user but hey wait a bit we are doing the request if I save and refresh this loading indicator will appear where but for a very small amount of time because the server is running on the same machine so the query goes very very fast but if the server if it would take a bit longer or I would have a slower internet on the device you this loading indicator would be very important for the user experience of our application and we don't have to manage it ourselves with separate State variables it's managed by the use Query the same goes with the error so error here so what we can do here is say if error then return let's return at the moment the text with error.message make sure to import the text from react native here at the top and um you can style it better but I just simply showed it in a text box and what I can do to simulate an error is I can go to our library here and maybe I can actually go to the config of our library to remove the API key so this request what it will do it will return an error because we are not authenticated here we can see very well the loading indicator and after a bit of time what we should see is the arrow fetching tweet and this is where them throwing of a new error is coming handy because that's how the error from our library reaches the error from the use Query other libraries other libraries like axios whenever the status code is going to be other van and OK status code like 200 or 201 both libraries will actually throw an error but the fetch does not throw an error so that's why we have manually we have to manually check the status code and to provide the errors here and it can be more granular like you can add a different status code here like if status code is equal to 401 then not o for raised please sign in for example so we're gonna specifically check like if it's for 401 it's not authorized if it's not 200 like there is an error but we don't know what and if everything is okay then return response to Json so if I'm gonna refresh now we should be able to see if it's not authorized yes exactly that's what we see here so back in our config I'm gonna do Ctrl Z to make sure that our requests are working and I think I should refresh it actually and we are back to our screen with data that we get from the server well one more thing is about this query key this query key is an identifier of this query that will help that will help direct query manage the cache how it will cache the result of this query so the next time in other parts of application if we're gonna do the same uh another query with the same key tweets then basically the react query will cache it into the same array so basically it will override the previous data that happens in another screen and it's powerful because when data changes in multiple places of a screen and this will help you maintain the same data without having to fully reload it so for example if you change the Tweet here and then you go to that tweet screen that is not yet implemented but we're going to do that in a moment but data will be the same when we are using the same query key it's also uh important to mention that we can add multiple query Fields here so for example we can say tweets and we can provide here another um another a string and the response will be will be cached based on the combination of this key what we can also do is provide objects here so any data that is serializable can be provided here so for example if tweets if we're doing a query for the tweet that also includes some kind of filtering we can provide here filter um my yeah my tweets and this is going to be different than we have a vendor query with only queries the Tweet because it also will include some other fields like filter okay in a moment we're gonna see one more way of how to add variables to this query key why do you use use Query lip I use Query which is via react query Library helps us as I was saying so far helps us query and manage them state of our application when the data is coming from our API so instead of doing everything ourselves which is in this comment here which only handles the minimum amount of logic what we do is using the use Query we can do everything much easier and also it has a lot of added benefits behind the scenes like caching and other important features that um that you need whenever you're working with remote data coming from your API so if you're interested check check out the documentation we have like them a guide here somewhere at the top like where should be in the docs we had a page with motivation and a I don't see it anymore yeah here on the home there is motivation and they explain pretty pretty well why you would need to use react query okay perfect so uh let's uh let's go ahead and do git add here because we have commit minus m setup react query and fetch tweets this is the first step The Next Step uh whenever we press on one of his tweet we are going to the Tweet detail page so what that means is that we are opening um the page from this tweet directory with ID and at the moment it's looking through the dummy data instead of that what we will have to do is to actually send a request to our server because on our server if we look in our founder client we have a request to get a query by ID so if we send this send eBay token is expired but yeah I have to probably change it so let's go ahead in our lib API let's start with the logic of fetching the data from a server so for that let's export const get tweet it's going to be an async function and also we're gonna receive the ID of a tweet that we want to query this ID is going to be string let's start by [Music] um let's go ahead and be a bit lazy and copy paste the code from list tweet because here what we will want to do is also we will use fetch API to query the API tweet but at the end besides slash tweet slashed wait will return as a list of tweets but if we do slash tweet slash ID that's going to be only one um tweet so let's go ahead and add the slash here with a variable ID we're including authorization token we're doing some basic error handling and at the end we are parsing it to Json perfect that's everything that we need here so now let's go ahead and open withdrawer tabs feed tweet idea and this is the page that renders one tweet what we're gonna need here we're going to need the use Query use Query from tan stack react query we're going to need the get query API method so that's going to be not get query get tweet from lib API tweets and putting them together what we can do is we can use Query here we need to provide the query a query key which should be as I said an array of strings or our data types like objects so I can say here it's tweet and we can also add the ID here because we want every single tweet to be uniquely identified in our cache if we only provide the Tweet here whenever we go to a different one it will override the previous tweet so that's why we need here the ID to make sure that tweets with different IDs are cached in different places like separately and the query function will be get tweet get with expects an ID so we can Define here a function and send to the Tweet the ID idea here can be string or undefined and so on I can do a string and what do we get back let's get back data is loading and maybe error We're not gonna have to find the tweets through the dummy data and also we can remove the import of that tweet let's do if is loading then return VM activity indicator that will show a spinner um if let's do if error then return to it not found otherwise let's render the component tweet with that data that we get back from our API so now if I press on this one my first tweet from founder client if I go back by pressing on this feed and if I open something else how are you guys and the cool thing um the best thing that probably I can show you here is if I take our backend from here move it to the other screen close to our iOS device and if I go to the Tweet routes and inside the list tweets no inside the get one tweet if I go ahead and say console log uh query to it with ID and here let's say ID I will add this console log in order for us to see how many times is our server actually invoked when we are using our application so let's go ahead and press on them actually Let me refresh the rec native application and press on the first tweet if I do that we see a query tweet with id1 okay that's expected because it's the first time we are opening a tweet if I go back to the home screen go to the second one we say queried with with ad2 okay perfect if I go back and go to the first one it still comes here I don't know why because I I was actually expecting it to take it from cash and actually not uh have to query it um but it doesn't happen so my expectation didn't meet the reality why is that happening why it's not uh taking it from cash I'm afraid that we will get into complication here but let me check the fetch policy let me look through the documentation for a bit Network Mode online offline first this mode is the middle ground between the first two options foreign caching let's see the caching basic the caching example is rating for story and life cycle of I think we have to configure it yeah since no other queries this query will show hard reloading State and make a network request since the cash already exists the data is immediately immediately returned but it also triggers a new network request okay so I understand how visc caching works it actually will not prevent the cache to reach the server but what it will do it if it already has data in the cache it will display the data without showing a loading indicator behind the scenes it will send a request to the server wait for updates then receive updates update the cache and update the UI so it will not prevent the request to reach the server multiple times but it will make the UI look much more Snapper because if it already has some data if it's not the first time it will not show that loading indicator so I think we can I can show that with in the Tweet route if I somehow do [Music] in the get one tweet here if I somehow wait for for a bit let's for example I will I will do that timeout two seconds and only then I will do response Json not sure if it will work actually and it should be the second one uh you don't have to do this I'm just trying to simulate a very long request so now if I go back here and open a tweet that has not been opened before one two and then we should see the data you see a very long loading State this simulated a long request so when it's the first time you're opening that tweet we are seeing the loading indicator if I go back and open a tweet that was already opened it will show the data that is already in the cache behind the scenes it will do a request to the server and we'll update the UI and we can see that if I go to the Prisma Studio and for the first tweet my first tweet from founder if I update here updated the text updated and save one change if I'm gonna press on this tweet we should first see when my first week from founder client and then in two seconds we should see the updated because the query behind the scenes is running gets back and we see updated there so I hope that makes clear like how caching works and um yeah it's I think very powerful to make sure that we are providing a better user experience let me move back this one here and we are ready to yeah we are ready probably to move to the next part but I need to make sure to remove that set timeout from the back end not to take a lot of time a quick tip if you're working for a client you can add this set time out and after two months go ahead and tell them like hey I improve the performance of a server so now the queries are much more faster and you can charge extra for that but don't say where you got this tip from uh okay let me go ahead and do it add fetch one tweet perfect foreign thank you I appreciate that Matt is saying this is the most proper Twitter clone tutorial ever keep I have a great work I'm going to eventually purchase one of your products thank you very much I really appreciate that I'm happy that you guys love that we go really in depth here if you have multiple apis to fetch how can I fetch all of them in react query well as I said the react query is really back and agnostic so it doesn't care where you get your data from because at the end of the day like what it what you have to do is you can you should provide an asynchronous function to the query function that will do the logic of querying so in our case we created this Library that is using the fetch API to do the requests you can also use axios to do the request you can use other libraries to do the actual requests because what react query is doing it's only managing the state of our data once it reaches our device hopefully that as first your questions foreign but if you say that you have multiple apis to fetch what I actually would recommend what would be better is to merge them together into one single graphql API and you can do that using step then we have actually a tutorial on that it's the building a books project in react native and that project is using stabzan in order to merge multiple apis together and create generate a graphql API out of different parts for example in that project we are querying data from books API and also from Google Google from Google Books and from some other API so if you have the same use case like I would rather recommend you to create one single API using steps in out of every single apis that you have here and then from your application is going going to be much more easier to query the data uh okay so what do we have here we are querying the tweets we are querying the single tweet the next step is to create tweet right because yeah when we write something here we should be able to create new tweets in our backend that is handled by the post request create tweet as you can see the only required field that you have we have to send to this request is the content and it's handled by doing a post request to our slash tweet endpoint let's go ahead and in the tweets start with creating uh the function that will do this request I can go ahead and copy paste the function I get with and let's call it create tweet the database it will receive is going to be let's say data and the structure the type of it is going to be an object where it will contain content of type string content it might also contain like images and other data but let's start with simply content now um what we have to do is to do a fetch request on the API URL slash tweet we don't have we don't need the ID here and to make it a post request we have to send here another Pro option method using post method post authorization and then what else the body right and the body is going to be our data but we have two stringify it so Json stringify data as the body containing all the data but we want to send to the server uh okay error creating tweet and then we can return response to Json okay let's see let's go ahead in our application and here we have a new tweet screen that contains this on press event now previously we saw how to work with queries queries are helping us get data from the server whenever we have to send data to the server and to whenever we have to update things like creating new tweets or updating a tweet or deleting a tweet in that case we should use mutations so let's go ahead and get the hook use mutation from thunderstack react query and in our component new tweet here let's go ahead and using our mutation use mutation what we should do is we should provide here options with the mutation function limitation function will be our create tweet function that in my case was imported from automatically from the lib API tweet the function that we just defined here in our library okay oh I don't have need here the arrow the notation now back from the mutation we're gonna receive a couple of functions for example one of them is the mutate function then we also will receive a loading and is error what we should do is here when the user presses on this button on tweet price let's go ahead and call the mutate function to send the request to our server here we need as we can see from the typescript we need to send variables with the content and the content is going to be our text that user wrote in the input box text text now here we can say let's show some kind of a loading indicator I can do that in between the cancel and tweet button and let's say if it's loading then let's show an activity indicator if it's loading and show of activity indicator for the error yeah maybe I can do it somewhere here or even be below the input container let's say if yeah let's do if error and I'm going to display it with a text error Dot message what's wrong here did you mean ease error there is also easy error which is a Boolean but there is also the error so we could work with both like here to check if it's Error and here to render the error message now let's go ahead and try it but hmm I'm gonna go ahead and comment out this set text and router back in order not to navigate back from this screen new tweet from the application if I press tweet error creating a tweet why we can go ahead and error creating a tweet I think creating a tweet gives us back the status code 201 no is 200 then what's going on here let's do console log response to see what response do we get from a server tweet status 400 . hmm is it because of the because we didn't provide the content type here so content type application slash Json I think it worked or no let me check them the studio new tweet from the application so that means that it worked let's try one more time if I go here and say testing to it I think it worked testing it's here and we don't have any errors so yeah the problem was we had to specify the content type which should be application slash Json when sending a fetch request okay back to our application here so what do we do with this router back because if we add it here the thing is that after executing this mutate which is synchronous function it doesn't mean that it automatically succeeded it means that we send the mutation but we don't know yet like we should still wait so doing it right away here it's going to um automatically redirect us back without waiting for a response what we can do is either we can add a user effect based on the is success to check like if in success was received as true then we can go back where we can work with mutate async and visma data sync is an asynchronous function but we can await and we can put it into a try catch because if we await it can also throw an error I think and if everything worked okay after the wait then we can update the text and navigate back and here we can add a catch that can simply console log the error because still the error is going to be received here from the use mutation as well so here testing now if I do tweet we see loading and then when we receive it back we right away are navigated back so I can delete the try from there and we add everything that we need here in this part we don't need VC success and and yes that's how we are creating new tweets as we can see here what you might also be interested in for example um update the feed if I tweet this update the feed you want to go back and probably you will want to see the update feed somewhere here what we can do is let's check the documentation we can invalidate some queries when we run some mutations for example updating a tweet should invalidate the query that got the data for that tweet and here like creating a new tweet should invalidate the feed so one way would be to query invalidation we can run query client invalidate queries and to pass where the query key on the query that we want to invalidate and where do we do that we can do that in them from rotation on success so for the use mutation we can provide here on success function when can using the query client that we have to get here at the top query client EOS client is it use client or use Query client let's see import it from react query probably use Query client yes so what we can do is when the mutation succeeds we can invalidate the query with the key tweets right because if we look at the drawer tabs feed index here our query key is tweet so now if I'm gonna do now it should invalidate the feed query and display this tweet if I do tweet I go back and if I scroll down right away we see the new tweet here at the bottom now it should invalid with feed query and display with tweet so this way whenever something happens and we know that some data will change in our application we can invalidate that one and when going back it will do another request of a server to update it but uh that's not the only way because we can also do um updates from the mutation response so instead of completely invalidating all the feed here what we actually want to do is we also we only want to add a tweet to that array of tweets because we don't want to query all of them imagine having hundreds of pages of loaded tweets you don't want to invalidate all of them because you're not it doesn't mean that creating a new tweet change somehow of other tweet it only added a new one to that array so what we can do is on success we can set query data with the data that we want also with a client yes yes so here in the new Tweed query client we can set instead of calling invalidate queries which I will leave it here we can set query data query key is this one and the function is going to be updater so existing tweet and we should return a new array with the updated thing so all success will also receive data here so what we can do is we can return a new array where we put data first and then all the other existing tweets and this way the new tweet will become will be at the top right I don't know let's see let me see set query data you can do it like this or you can also hold the data if you but it can also be let's see existing tweets thank you the array of representing the key oh it's a bit different so it doesn't have its queries just has the array representing the key is it set query data key and then a function that updated array invented function which is unknown okay let's uh let's see it might be simply a problem with with types but it might work actually so here if I refresh have everything like this should be displayed at the top of the feed if I tweet it go back no cannot read property image off undefined on success data exit let me go ahead and do a proper function that will return this and here I want to do console log data and console log existing without destruction let me just do it like this oh not here yeah uh so if there is updated one two three tweet and why do we see there data is the new the data of a newly posted tweet and existing is an array of data oh I know the newly posted tweet does not include the user that posted it so what I can do I can go back to to my back end for them tweet route when we post a new tweet create tweet I can also do it create I can also include the user of this data to make sure that when we return it back it Returns the user of a tweet as well because that's what we need to automatically insert it in that feed user data tweet and we see with it right away is displayed here as user data perfect it doesn't have a name because my newly created account with an email by dim Sabin does not have a name in our database so there's only reason why if I add the name here and change it like this what going on okay this one my team save update and the data should work yeah the last one is by dim and if I do new one send at the top of our feed it says new one perfect so we saw two ways of automatically updating our queries based on the based on some rotations that we are running using the invalidate queries which will simply invalidate the query and the next time we go there it will do a new request to the server or by uh writing automatically data that changed in the existing queries that we have amazing let me go ahead and oh why did I stop the server create tweet mutation I forgot to add yes and that is how we can run mutations and send data create things on our server okay what else I think we are mostly done with um basic query and mutation I showed you how I can query list of items I showed how we can query um one item by D how we can do mutations how we can invalidate how we can how the cache is working and with it being said I think it's time to get into the Authentication well authentication is going to be interesting and it's going to take a bit of time to implement and explain everything so really excited about that what do you guys say how is it going so far uh John uh no I haven't worked with grpc hello this example keeps session active even when you close the application um we haven't implemented authentication yet but we're gonna do that and also we're gonna make sure that we keep the session active even when you own close the application can you use access for grpc requests not sure about grpc but you can use access with react query all right thank you thank you very much all right is types really required or can I watch it with very basic typescript knowledge you can definitely watch it and follow along with basic typescript knowledge if you understand what part is the typescript you can simply ignore that if you don't want to to use it and continue using JavaScript it's as simple as that ha do to okay so next step authentication are Authentication let me just bring some water and then we're gonna get into the Authentication so great come on boy you can't do it um all right yes gives me a bit more energy all right so let's get into the user interface of our passwordless authentication flow what we have to do is we have to develop two screens in our application one that will start the request that will request a one-time password and the second one where the user will be able to input the one-time password and receive the JWT token that the application is going to use to perfect sign requests that he's going to make to our server so yeah let's start by developing these two screens the user interface then we're going to make the requests and lastly we're gonna make the logic of handling protecting our routes and handling the authentication flows so in our application what we have to do is let's open our up directory and again like for our visa application that I'm using for this demo we are using Expo router but if your application is using something else you can completely use a different rack navigation as well for example so let's go ahead and here create a new group of files that will handle the authentication so let's create a new folder of and here we're gonna have two screens one of them let's say sign in screen sign in dot TSX and power1 is going to be the second screen that where users can input via email code so on the back end we call that authenticate.tsx so let's keep it the same let's define two Basics components here react native function export and here react native functional export should be capital same here as a temporary solution how in the indexed I'm going to redirect actually to our sign in page in order to see it always on the screen so if I'm gonna refresh right now we should be redirected to the sign in and here we see this sign in text foreign page what we need is we need two things we need one text field where the user will be able to input the email and a button where he is going to um that he'll press to start the flow so let's go ahead and start with a text input so Define a text input and here for the placeholder we're gonna use email let's make sure to import text input from react native like this thank you why is Spam feed display there okay sign in and for the text let's do sign in or create an account because this flow will both sign the user in or will create an account if he doesn't have one create an account lastly what we're gonna need is a button at the bottom so let's use a pressable component from Rec native and inside the pressable text saying sign in like this okay four of the Styles I'm gonna go ahead and provide you with all the styles that you need so you not to waste time on the Styles like it's pretty basic but still it it would take us a lot of time so style should here and let's go ahead and provide to web top view Styles dot container then for the text Style dot label for the text input let's give input pressable will be style Dot button and lastly here button text and just like that we have a pretty simple page where we can write our email that's not everything because we have to um bind a spade variable to this text input to get the email that user is typing so for that we're gonna Define the email state foreign and initially it's gonna going to be an empty string let's make sure to import Q state from react and the email value we're gonna send to our text input as value so let's say value equal to email and on change text is going to call our Setter so every time we change the text it's going to update the state variable now if I write yes it everything is working and the pressable we'll call a function that we have to Define here so let's do on sign in is going to be in a sync function that at the moment let's simply console warn sign in and maybe even the email let's make sure that whenever we press on this pressable we on press we call the on sign in function now if I write my email here press sign in we see my email at the bottom so with a user interface for our sign in page we are I think we are done so let's go ahead and copy everything and move everything to authentication as well because the authentication is going to be another page that instead of requesting the email it will request the user code so what I will do is in the index let's do the redirect to the slash of fan decade to make sure to see it here on the screen any side of indication what let's start by changing them State variable from email to code set code and here the user will be redirected automatically and he will be able to authenticate using this code text input the placeholder will will be email code set code and we'll confirm your email maybe you can provide extra details like hey we sent an a code to that email and that's what you have to add here if you want to provide more details in here instead of a button sign in confirm on sign in let's do on confirm your email and here you'll press email code one thing to note is that when we assign this authenticate request of a server using the email token we also have to specify the email so one way would be to have a text input for the email on this page but that wouldn't be very user friendly because in the previous screen he just wrote the email so actually from the index let me go back to the sign in screen and in the sign in what we want to do is the email that the user will write in this field we want to send as a parameter to the next screen so the next screen has access to it and doesn't ask a user one more time for the same email so how do we do that first of all let's see how we can navigate from this screen to the second one and I'm going to import use router from Expo router and here we simply do router Dot not yeah firstly we need access to this router so at the top use router and inside vowel sign in function we can call the router Dot push and let's push them authenticate screen so now if I press on the sign in here we should be redirected to authenticate and now I can go back to this one and so on but how do we send data there well to send data we can pass here instead of a string an object and v string will become the path name and the second parameter we can add params here and one of the params can be the email now we are sending this email there but how do we get it in them next screen in Expo router we get that using them use search params from Expo router so let's get the email from use search params so here in authenticate let's try to console log email and code now we are on the sign in page if I write here ABC Sign in we are redirected to the next one and here if I will write one two three confirm as you can see the console log here is authenticate abc123 which means that at this moment in time we have access both to the email and to the code that exactly what we will need here to authenticate and get back the authentication token okay Okay so so far we have a user interface of authentication let me quickly get add git commit of UI maybe not yet I wanted to maybe update a bit we have titles and the headers of these pages so to do that in the root layout I'm going to add a new stack screen here stack dot screen the name is going to be the name of this route so authentication is skipped because it's within parenthesis but in these cases sign in so this way I can provide react navigation options to my sign-in screen and for the sign in I want probably to hide the header so header shown false and let me copy paste this one one more time for them I'll authenticate and instead of hiding the header I'll provide a title confirm I don't know and if I refresh it doesn't work oh actually it should be of indication slash yes because there's the name of it it's not the path of the screen but the name so now the first one doesn't have a header the second one is going to have a header with title confirm and I can go back from there awesome now I can go ahead and commit yeah okay so once our user interface of our authentication screens is ready let's go ahead and implement the backend requests that we're gonna need to interact with our backend so for that I'm going to start with defining a new API Library here for our authentication.ts and here we're going to have two functions one of them is going to be the login function which is a sync and as a parameter it will receive a email not email but data which is going to contain the email and the second function that we're going to need here is the authenticate which again is a sync it will receive data but in this case the data will contain both email string and also them email token string let's make sure that this data email and email token is the same as we have here email an email token perfect so let's go ahead and implement this uh these things what we will need here is the API URL so let's import API URL from config which is a file here with a URL now with localhost but if we're gonna host the backend it's going to be changed and forever login what we have to do if we look in our backend we have to send a post request to the slash login page using the email not page but endpoint using the email as the body okay let's go ahead and do that response equal await fetch what do we want to fetch we want to fetch a combination the API URL then slash authentication of Slash login I'm taking this one from this URL and for the options what do we need there well first of all let's provide the header with the content type which should be application slash Json and we don't need the authentication header here because this this endpoint do not require the user to be authenticated yet that's what we are doing with request but what we need is the body so the body sit here yes the body is going to be the Json stringify version of our data that we receive as parameters data like this okay let's do some basic error checking because if the response dot status is different than 200 if there was an error then let's go ahead and throw a new error errors during the login process otherwise doesn't have to do anything we are simply returning okay okay let's copy the same logic in the authenticate because it's going to be pretty similar so what we will do is we're going to do a fetch on the off dot slash I'll fin decade so if I look here authenticate is going to be post request on the authenticate email and email token and I think I forgot to send the method should be post and the same here for the second one method post so with stringify the data we send it if it's not 200 there was an error otherwise let's go ahead and return the response Json because it's important it contains both indication token so let's return their response dot Json like this okay uh so with a low level logic of fetching our API we are done and we can move on to our screens let's go ahead in our over navigation to the sign in screen and this is the first step so what we have to do is we have to Simply import this login function from our API and call it here when the user presses sign in uh you can directly call that function here without any other additional libraries but because in this project I am using react query I'm going to continue using it for for running this mutation as well so I will simply have to import use mutation react query let's Define the use notation here simply provide the mutation function should be a object with mutation function and the mutation function is going to be the one that we defined here in our Library login so it should be log in you know what because we are going to hmm you forgot method post thank you very much I'm thinking whether to use a react query for this process as well thinking about this video I want to release as a separate independent video hmm okay let's let's use it hopefully it's not going to be too complicated because at the same time like for for these two mutations like it doesn't add a lot of value and I would actually let me do it without a react query in order to to make this passwordless authentication videos more generic so anyone can Implement in their stack so what I'm gonna do is um yeah continue without bam react query so now in our sign in function let's go ahead and import the newly created login function from our library API authentication and what we have to do is here on sign in we are going to call login function and we're gonna send the data with our email let's make sure to await and because this login function can throw an error we have to put it into a try catch try here we're going to put the router push in the try because we want to navigate to the second screen only if the login succeeds and in the catch we can catch the error and simply using an alert we can provide alert alert error and we can do error.message make sure the import alerts from react native I am doing here very basic error handling using an alert but you can save it into a state and display it on the user interface as well so now in our application if I'm going to use my email here it actually redirected to to them oven to the confirm page and if I look at the back end in the logs we see that right now a couple of seconds ago we received a new request and everything was successful Okay so let's do the same thing on that confirm on them confirm page on the authenticate page and here in the confirm what we have to do is we have to import the authenticate from our library which is the function that we which we'll call our backend and inside our own confirm function let's go ahead and do a try catch first again very basic alert error handling let's make sure to import alert from react native and inside this try what we're gonna do is we're gonna call the authenticate method we're going to send here the body containing the email and the email token Vmail token we're going to take it from the state uh here typescript is complaining because VC mail from search params can be either string or undefined so I can do a check here if type of female is different than a string I can return here and let's go ahead and console log their response to see what we get back okay so if I press sign in here we already directed to the next page if I do some kind of code press confirm email code doesn't match but if I'm gonna use the code for that I received on email which is this one confirm within civil alert and if I will look in the logs we should see this log with the authentication token and this is exactly the authentication token that we will need for next request to authenticate our request to our API so that means that the whole flow now is connected and working properly from creating an account and requesting a one-time password on our email to validating that password here on the second page and exchanging it to a JWT token the only thing next is to save his jfwt token uh somewhere use it for the next requests and also to manage the whole uh authentication flow and protect some some of our application routes based on whether the user is authenticated or not okay let me go ahead and git commit Authentication authentication backend integration and our next step is going to be foreign let's um let's see give me just one second Expo router the next step is to manage their authentication flows in our application and to protect our screens based on both indication status of a user so if a user is not authenticated we should always redirect him to the sign-in page and if a user is authenticated we should redirect away from a sign-in page to the home screen for example and at the same time protect the users from being able to navigate to the routes that he should not have access unless he is authenticated so I will leave a couple of links to the guide of this authentication flows so if you're using rack navigation there is this guide for authentication flows that explains how you can display different screens based on the authentication status but in our case we are using Expo router so we're gonna follow this guide for the authentication that will help us implement it using them export router uh so I don't want to Simply copy paste everything I don't want to Simply copy paste everything so we're gonna develop it step by step together so what we need first is a context that is going to contain data about our authentication status which we will be able to use in all our screens to know like is the user authenticated or not let's go ahead and create a new folder context that will contain files with contexts the first one is going to be of context dot TSX okay First Steps first is let's define this of context using the create context function from react like this now let's define a provider so of context provider is going to be a react component that will render the out of context dot provider here and inside of a provider we will render all the children that we will receive as the as the children of these old contacts provider when we will encapsulate our screens with it so children we can do props with children and here we can go ahead and render them here the off context provider expects a value which will represent like the actual value of our context and what will we store in this whole context well um but most important thing is we're gonna store them the token the JWT token so for that we're going to need the state variable for the off token set of token which is equal to use I'll use state and initially it's going to be null visual State should be imported from react so use state and if we provide also types it should be string or null let's go ahead and explore this off token as a value and should we also export the set authentication token Maybe let's go ahead and set it exported it as well make sure to export this off context provider component as default so export of context provider and we need to do it by default and what we're going to do with it we're going to wrap our whole application inside this of context provider so in export router that is going to be in our up layout file and let's import of context our context provider and let's go ahead and wrap our whole application in of context provider like this inside our root layout navigation um now in our authentication screens specifically in our screen where we receive the JWT token we should be able to update the authentication token from our context provider basically we need to get access to this context and to call this set of integration token that we export here what we will do to get access to this context is we're going to export a const a custom hook called use authentication which will help us get access to the context using the use context hook and by providing these contacts these specific context here use context Hook is in our hook that we need to import from react and now using this use of mitigation we can get access to the set authentication token function inside our authenticate page here the name of this function should be of authenticate actually export default off indicate and using that hook we can get access to equal use of set of token so using this sector we can go ahead and call set of token with a response Dot what's going to be the off token that's going to be them value of our response that's what we saw in the com in the logs so let's go ahead in our context and do a console here to make sure that we are properly setting authentication token so console .log of token equal of token so now if we look in the logs we should see yeah let me maybe clear if I refresh we should see off token node because we are not yet signed in that's okay let's go ahead and simulate a user creating a new account for the confirm code I'm going to take it from my email confirm and we see that it automatically updated the off token in our context and yeah now it has an authentication token perfect but at the same time if we have an authentication token that means that we are authenticated and we can safely redirect the user back to the home page right so how do we do that well we will do that um using some listeners and using some effects based on authentication token and also based on the URL where the user is currently on what I mean by that is let's get there how's it called them the segment the segments of the path from Expo router use segments from Expo router it was imported automatically and if I do console log here segments should be segment you're gonna see what it contains so this array contains the segments drawer then tabs then feed it's basically all the parts of a URL that are separated by the Slash and in our project that represents our directories so as you can see the drawer is drawer then tabs tabs then feed feed if we are on the authentication page this contains authentication then sign in so this is a way to understand on where the user currently is So based on these two things where the user is and whether he is authenticated or not we should we can understand like if he is supposed to be there or not or where he is supposed to be in terms of what screens so let's do a use effect on vent will always be executed when either of a segment or the authentication token is going to update to understand if he is currently on some screens that do not require Authentication basically is of group we can check if segments at position 0 is equal to authentication to off like this because that's our first part of a segment for Wolf integration screens then what we can do then what we can do is we can decide where the user should be so if the user is not authenticated so if authentication token is null and he is not involved integration group that means that he is on a screen but he is not supposed to see in that case what we should do is we should redirect him back to the sign in screen to redirect we have we need access to the router so use router from Expo router and we're going to use not push but router dot replace because we don't want him to be able to go back to some screens so replace slash how is our authentication slash sign in sign in otherwise also otherwise if I can do another if statement here but if he is authenticated which means that he has an authentication token and he is in the authentication group that means that he shouldn't be there he should be on the home screen so router dot replace and let's redirect him to the feed or even to the home screen like slash but if we redirect to the slash we should make sure to go to our index and Define the home screen as the feed it will still redirect back to the sign in because we specify that and we can have a look in our off context and say console log user is not yet authenticated and he cannot see this page so right now if I'm gonna refresh the page and look into the logs that's exactly what we see user is not yet authenticated and he cannot see this page because the segments if I will also run console logger segments we will see that we were on them feed screen but now if I'm going to sign in by the not just the dev get the code put the code here and press confirm now I'm redirected home and how it happens it happens because router replaces our screen with the Slash and invest slash which is our index radio access to the feed and now we cannot go back because we are already signed in the thing is that if we refresh we're still gonna go from the first part part because we are not um persisting the JW JWT Tolkien our authentication token yet but at least our authentication flow is working properly as we expect it to work so when there is no authentication token and the user is not in the authentication group we want him to redirect back to the sign in page and if he has the authentication token and he is still involved in the gation group we want to redirect him to the home page to the home screen so that's how we basically gatekeep different screens based on the authentication status of a user so let me do get odd git commit off um how's it called protected routes okay we have two more things to uh to do we have to first of all persist our authentication token so every the second time we're gonna refresh the application We're not gonna have to go through the same process again our application will remember that hey the user was signed in and will write this authentication token in storage to do that we are going to use uh we can use some libraries that will help us write on our device storage we can use a sync storage but that is not a secure way to store tokens a better way would be to use Expo secure store and this will allow to store data on the storage which is encrypted so to do that we're gonna install firstly Expo secure store in our work native application and tax export install and using the secure store dot set item I think and get item I think we're going to be able to write and get the our authentication token so where should that happen that that should happen in the authentication of context provider and first of all we need to save that token whenever we are updating it here so instead of manual instead of directly sending the set of token Center function I mean instead of exposing the set of token function here what I will do is actually let's go ahead and do um update of token this is going to be a function that will receive the new token as string and we're gonna expose this update authentication token from here we want to make sure that in our screen authenticate we are not calling the set of token but update of token and in our off context what we want to do here is let's go ahead and first of all set it in state set off token in state and also we want to to save it on the device storage using secure store so for that we're going to import cure store not like this like this and yeah besides saving getting State we will also want to do a weight secure store dot save set item I think here we need to provide a key and a value the key is going to be of token and the value is going to be new token I'm thinking to do it our way around to first save it on the device storage and then update it in state because doing updating in the state will redirect the user so yeah let's make sure that first the token is saved and then it's redirected and because this is an async function in the authenticate screen we should also make sure to wait here to update the authentication token perfect the second step is reading this authentication token when the application mounts so to do that we're going to add a new use effect with an empty dependency list that will um law that will load the off token so load of token is going to be an async function that should be called right away and in visasing function let's do const response as well we're gonna await the secure store using get method and using the same key we are going to be able to access it from the secure store so what we can do is we can set back in a state set of token as response we can do a if statement to make sure like that it's available before we set it in state like this so now refreshing uh and pressable and handle rejection let's see why is that happening cannot read property get item I think offline defined I think I've imported it incorrectly yes I need to import everything as I need to import everything as secure store from Expo secure store and now let's try to log in again sign in here we're gonna receive a code on email I already should have so many emails from this live stream confirm we are redirected to the home screen and hopefully we also persisted and saved the authentication token on the device storage and if I refresh the application if everything works we should automatically be redirected to the feed and that's exactly what happens we are automatically redirected to the feed so if I update refresh right now we are back here perfect so now the user will not have to always log in he'll log in once and the application will remember the authentication token and we'll use that authentication token for future requests so let's go ahead and Commit This and in the next step is going to be to actually make sure that our API is using the authentication token from Context provider because right now if we're looking in the config here then that was manually set here so what I'm going to do I'm going to remove this authentication token from here because it shouldn't be hard coded it should be taken dynamically and let's think how we're gonna get this data in our in our functions for valverization because now we're not going to have access to this authentication token so uh here these are functions we are we're not going to be able to get access to them to the context so most probably we the easiest way at this moment is to let's let me check let me check can you access react context data from API functions I don't know react contacts outside of a component um hmm yeah um at the moment this authentication token probably like would have to be passed here to to this function or or we can do another context that will provide these functions and in that case we will be components so we will have access to the authentication token let me see let me think thank you for your four day Master Class I'm very appreciative thank you very much for for the kind words [Music] how would be the best way so I have two options at the moment passing authentication token through properties through variables but in that case we would have to do that for every single query and that's not very user friendly or another way is to to Define them to export this from a from a from another context that is going to have access to Authentication hmm foreign or I could always read it from the store which is not something that I would like to do here as well because it wouldn't be very efficient think for them think think foreign so where do we let me see list tweets and so on in the new tweet yes here we can get that token and we would have to pass it there foreign okay so look what we're gonna do because our API methods they need access to authentication token as I was saying before we have two options of getting Visa authentication token in these functions one of them is for parameters because our authentication token is provided is available through our of context so so there is no easy way to get it directly here in the list tweet because these functions are not as part of a react 3. they are being called from the reactory and in that moment for example in the new tweet here we would be able to get the authentication token and send it down to the create tweet function but I really don't like this approach because it will imply that every time we are using them we are using mutations or queries every time we would get the authentication token so I think a better approach is to transform these functions into a react context as well and this way the functions will men will have access to authentication token themselves so they will not depend on extra parameters so let's see how we would do that so first of all let's say this is tweet tweets API context it's a create context we're going to create a context with create context from here let's go ahead and create that tweets API context provider and this one is going to be a function that will receive children and will return back the tweets API context dot provider and let me close this one it doesn't want autocomplete because my file is not a TSX file but it's um TS file so I can rename it to TSX tweet context provider and here let's go ahead and add the children we need to provide the value here and the children can be typed as props with children now what we can do is let's go ahead and bring all these functions I'm going to copy all of them let's bring it as part of this component and because we are part of this component we don't need the export from here like this now because we are part of a react component what we can do is we can use the authentication context and we can get from wherever of token like this use of that is a context managing the authentication and now our list with and so on we will men they will handle authorization themselves and the last step is to go ahead and Export them inside this value so list tweets get tweet and get tweet and also create tweet so we are exporting this way via the the functions and lastly I also want to export from here a helper hook so const use tweet API that will get us access using the use context to this tweets API context like this now we need to wrap our application inside this tweets context provider for that we need to export it as default export default tweets context provider and inside our layout we're going to import similar way how we did for our authentication context for our tweets API context provider and let's wrap it our screens in these tweets API context provider but make sure that it's below the authentication context because our API is dependent on Via authentication token so it's here and let's go ahead in our application where we are using for example in the new Tweed instead of importing it like this from API tweets we are going to import the used tweets API and we're going to get access to that function create tweet from this use tweets API hook like this and the same way in our drawer for example tabs feed index instead of getting list tweets from there we're gonna get used to its API and we're gonna get access to the list tweet from the use tweets API and same way as in between with the last place instead of get to it and this way it's loading loading loading I think it's it's gonna fail but we're gonna see why let's go ahead in our lib tweets TSX here and try to console log this uh off token so it's there but it's still saying not authorized let's try to see if this token is actually working by calling list tweets and changing here the headers the authorization header send it says 200 okay why might it not work list tweets of token so inside least tweets it's null why is it no inside this function is it about to end uh if I fix this issue probably yes but uh yeah we still have a couple of features oh why is the authentication token null here inside this function list tweets this function should be recreated whenever the authentication token changes but we are somehow not recreated uh pass this paramsin function what do you mean thank you these component should re-render every time authentication token re-renders but for some reason their functions are not recreated whenever we do that and they remain the same from the first time so that's why it's available here but not available here because this this function was created basically earlier and it's not updated but why list tweets I can try and use callback option use callback that also expects a parameter here and I can add off token to make sure that the list with function updates when both application token updates still doesn't work foreign thinking whether it's not updating because it I I don't think like that where should vet how it should work but I'm thinking that it's not updating because this is not a local state so it doesn't but it should update because it's a different so it's still updating actually so I'm gonna do a a test like let's try to add a local of token set local of token use date nothing then in a use effect so weird uh we update we call this use effect for number of token has changed so we can set local of token with of token and now we can work with this of token in the list I don't need fam callback because I see that it doesn't work it's still the same um yeah Mighty but in that case you'd have to send the authentication token and I wanted specifically not to have to send it from outside why ah that's that's hard that's tough and it becomes frustrating token inside API provider null inside list tweets null wait a second um exactly at least it's no no no oh my God it was doing this queries even before we load the authentication token and because it was scheduling this request multiple times it was always doing them with null and until it reached the point where it had it was no longer doing these requests so that's why in all of these functions we should make sure to go on check first of all if authentication token is there and only then to fetch otherwise to to stop the fetching process like this and yeah I can go back to this structure again tweet data is undefined but you should wait wait until look if um I'm gonna do it a bit differently like if authentication token is not here no I cannot do that it does this request even before how it has to do it um tweets data is undefined that should come somewhere from draw word tabs feed index and which data is undefined yeah I think I can do that so in there for example in the drawer thank you very much for the suggestion in the drawer layout here um I know that all of these screens are screens that depend on the authentication token so I can get the off token from the use Authentication and as long as we don't have authentication token yet I can return an activity indicator in this way we're not going to even get there and now when we get there we know that we have an authentication token and now it's working perfectly yes okay that's good that was a bit complicated but we finally managed to do it but the complication was from the combination of all our ways we are querying our API uh okay so let's go ahead and do git add git commit minus m Alpha use token from context all right that was tough but finally we managed to do it and with that being said uh everything that I have prepared for today is finished let me quickly do the outro for our authentication videos alright guys so I hope you enjoyed this video where we implemented passwordless authentication flow where the user is able to sign in in our application using his email only so it was a quite a challenging process but I hope you learned something new today and if you enjoyed this make sure to subscribe to the channel and turn on the notification Bell for not to miss any future videos that we're gonna make all right if you have any questions guys uh now is the time else I'm gonna start preparing for I have a trip to to Poland and every time like I go through these debugging sessions which is quite annoying especially in the during the live streams like it frustrates me but I see a lot of comments like um like Sandile is saying I know it's annoying but glad to have seen the debugging session and I I saw that a lot of people are taking value out of these debugging sessions but it's killing me thank you very much all right guys so thank you very much for staying till the end um stay tuned we are going to announce the new projects that we're gonna do if you want to see how you would deploy this backend to um to to production let me know in the comments maybe we can prepare something for that as well take care stay hydrated guys and I will see you next next week probably
Info
Channel: notJust․dev
Views: 8,810
Rating: undefined out of 5
Keywords: vadim savin, not just development, notjust.dev, react-native tutorial, react native ui design, react native live coding, live coding, javascript, react tutorial, react native tutorial, javascript tutorial, react native ui, react native for beginners, CodingTutorial, first app, App Building, App Clone, Step-by-Step Guide, User Interface, Twitter, Backend, node.js, frontend to backend, connect frontend, React Native
Id: 48UTHmf_Tp0
Channel Id: undefined
Length: 179min 23sec (10763 seconds)
Published: Tue May 09 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.