How to fetch data from API in Next js 14 +?

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
welcome back to ACH in this video I'm going to show you how to fetch that so let's start let me quickly show you what we are going to cover in this video we will install the project uh I will guide you how to install a project and and then we will open the vs code then we will choose an API to send a request by using fetch API I use by using fetch function and I will be using Json placeholder that is a free fake API for testing and prototyping and then uh we will create a custom component using users. ESX in the components directory and the purpose of this component would be to display the API data then we will display the fetched data by passing data to the components and we will map data to the UI elements okay then uh we will also discuss about how to handle uh the fetch errors uh I will show you how to I will uh demonstrate by using TR catch uh in the server actions and we will also show you how to redirect if there is an error and I will also show you uh how to handle errors with the error. TSX so we will Define a uh an error boundary by creating error. TSX in our fold in our app directory and also we will quickly style the UI that will display the data that we will fetch from the API and then we will deplo the project to the versal and I will show you the each step for the deployment okay so let's begin so first of all make sure you have your project set up and ready and working in your editor if not then you can create a new project by running this command npx create-x app at latest by running this command this would ask you a few questions like your project name and uh if you want you want to use typescript Tailwind CSS Source directory and app direct directory so opt in for the app directory because that is what we are going to use also select the aent CSS as well in those options once your project is created you have to open it in your favorite editor we would be using the VSS code in this case once that is done uh we will uh use the Json placeholder so let's do that uh let me show you my project this is the project structure that you can see and here in the page. TSX I will just get rid of the generated code and just add a simple code okay okay and now let me show you in the browser so let's reload it okay you can see it is visible further uh in the global. scss you can get rid of the generated code if you want from scratch okay now let's get the data so here I will create a function get users and we will add the fetch method in it and call this endpoint SL users from the Json players holder and here you can add async to get rid of the dot then chains and here let me use a variable response is equal to a weight and actually a weight should be here okay after that we will convert it into the Json by calling the Json function and then we will return the data okay so now here I will call that function let users is equal to wait get users and in order to use a weight here you need to add async in front of function and once that is done uh I will use the users so let's add the heading users here and here I will use the map function to display the list of the users so here I will use users. map user okay now let me display the data so here we will add type any save it okay now let me show you here all of the users are are visible tailin CSS is installed that's why it has reset all of the basic styling from the browser I have commented that out and now you can see the structure is looking really good now so let me quickly explain this page ESX is currently uh a server side component and this is a this function is basically server action so with the addition of server action you don't need to create the separate APA endpoints you can just make use of this and and directly access it here so you can use the server actions in the uh client components as well so for that let's suppose this is a client component here you will add use client and if you want to make it client then you will have to remove the async from here and here you need to add the use State let users set users and make and import the Ed state from the react and now you can cut it from here and let's import the use effect and call it and this should be this function should be called once the component is mounted and here in the second parameter we will add the empty array so that it could be mounted uh only once it could be executed only once when component is mounted and then I will add uh get users and here you can use then and once we receive the data we will set the users with that data okay now you will notice that it is still working but right now this is not a server component this is not a server action right now let me show you why I will show you in the inspect element go to the network and now reload it okay and here you will notice that the uh requests that are going to the Json placeholder are visible in your network anybody can see that you are sending request to this API so that's why that's mean it is not a server action it is not happening on the server it is happening on the client side so if you want to hide this logic you don't want to show it to the users you can simply uh open the page and in your function here you will have to add use server here with that this would become a server action okay in this way your logic would be hidden and it would not be included in the client side and okay so here even if I added the use server here it will not allow me to use that because you cannot Define the server action inside the client component so in order to make that possible you have to create a server action separate in a separate file so here in the app directory I will create another folder you can add lib actions and within the action you can add all of your actions so here I will create uh users. TSX RTS and within that you can let me make a TSX and now we will move our logic outside of this function let's cut it from here and paste it here here and you can use use server only inside the server components but if it is a client component then you cannot add it in here now as we are in a separate file so no need to add use server here you can simply add use server on the top like that okay and now we need to import the get users so let's import it we did not export it yet so let's export it in this way okay okay now let me reload it and I will show you what is the difference now there are some errors as well it is saying that fail to fetch let me try it again but other than that you are able to see that now the request was sent the data came in but uh we cannot see the underhood logic uh we don't know we cannot tell from the network that if request is being sent to the Json Json placeholder okay here if you want to handle it by yourself you can add try catch block so let's go to the user user here uh we can do this try paste it here and then use catch block and here and now here we can return an error message like this okay and here you can add any to get rid of the error okay now let's try it again let me reload it now it is saying undefined is not a function so here I'm returning an error property in the that object so here in the page. ESX we'll get the response users here here we can check if we have user are not in the response so we can check if data. error then written in the console otherwise set the user okay and now let's reload it now you can see there is no error even in the network there is no error okay because now we handled the error properly uh so in the console the errors are being shown because we have displayed the console error from here you can use console log as well to display the error so let's reload it okay we got two two error messages saying fetch failed okay uh let me tell you why it is not working properly sometime it works and sometime not and we are getting this specific error uh fetch failed and if you go to the network you will see that it is saying that resource was requested insecurely and in the preview you can see it is saying fetch failed so this actually normally happens in nowadays in modern browsers uh they apply a security if you are using HTTP and sending request to the https or if you are using https but sending request to the HTTP they sometime block your request so they don't allow that uh so in order to fix that for now you can remove the s from the HTTP because now we are using HTTP Local Host okay if you do that it will work fine save it and now let's open our browser and let's reload it okay this time you can see there is no error anywhere let me hard reload it okay after hard reloading that we can see that that uh there is not same kind of error again and everything went very well without any problem even if you open this you will see that we are getting the response in the preview okay all right so our data is now being displayed correctly so this is a new thing that we learned today so let's see what we have covered so far we have created the server action we also have used the tri catch block you can see we're using TR catch here and in uh let's say if you want to redirect user to some other page uh then you can do that as well for example I create another page quickly here in the folder test and within the test folder I will create a file page. DSX and now let's create the page component if there is an error you can also redirect user back to some other page if you want to like you will import the redirect and pass them to the actually the redirect should be imported from the next / navigation and redirect them them to the test page and now let's test it quickly here I will make the URL incorrect save it now reload it okay you can see it has redirected me to the test page okay when it redirect it does not return anything to the page here so in that case the data gets undefined so if there is undefined then you cannot use the dot error here okay so you can check that if there is no data or if there is data but there is error property and here you can add question mark here if you want to now save it now let's reload the homepage and this time it has redirected us to the test page without any error message okay all right we have looked at the redirect as well now we have the revalidate path okay so when you redirect uh someone to a specific page uh you can also trigger the revalidate path that means uh it will destroy the cache for that page so for example you created an invoice and now if you simply redirect user back to the invic page uh they will see the old invic even if you have created an invo so if you call that function before redirection they will destroy the cache and then that invic page has to uh re uh resend the request to the server to get the latest invoices in this way you can uh forcefully get the latest data okay we have covered this next we need to talk about this uh uh strategy about handling fetch errors so we have I've talked about uh the TR catch but there is another approach that is error. TSX so in this way we create the error boundary so for that we have to create the error. TSX file so let's quickly do that so here in the app directory along with the page. TSX I will create a new file error. TSX and as it mentioned here that it has to be used it has to be client component otherwise it will not work so you must have to add use client in this error page and now let's create our component error component okay now uh this will accept two props error and reset so here let's receive the error and reset okay so reset is basically function that we can call okay here let's display the error here error. message okay now we will intentionally produce an error and see what happens then because whenever you throw an error uh this error TSX would be triggered automatically so let's quick try here uh before the try cach block I will directly throw an error we save it now let's open the homepage double click on that press enter and we got an error in order to test the that error. TSX file I need to convert it back to the server component so let's remove all of these things States and here we will call the users const users is equal to get users we have to import import this function from the user action so make sure to import it we already have imported that now you can add the AIT here async okay now let's uh reload it and okay now we can see that error page is visible when error happened it will display the error me page in this way but right now I cannot see any message so there might be some other structure of this error so I can simply stringify that error message and display it here so use Json do stringify error save it and you can see this is what we are getting we can simply say something went wrong okay I did a mistake here instead of this we should have receive it in curly braces okay like that and here we will receive error and reset okay now if you remove that something went wrong you will see the exactly same message that we sent you can see this error is basically coming from the server action that we sent from here okay so let's say if I change the error save it then you will see a different error okay and after that let me add one last thing after that that would be button and here we will add retry and here we will add the click event on click and here we'll call the reset function I passed the reset function so it will call it automatically now let me reload it and let's clear everything before we try hit the network and clear everything now let's click on the retry and you can see it uh retried all of those request it retried that server action as well but as there was a general problem we thre the error intentionally that's why again error happened so in some real world cases uh sometimes server is down and you get an error and uh if you want to give user opportunity to retry you can give them this button if they click on that the same request with the same payload would be sent to the server again and in next attempt it might work for them so this is very helpful in that case so as it is written this is function to reset error boundary error boundary when executed the function will try to reender the route segment okay next is styling the UI so we already have covered almost a lot of things so let me just RT the errors from here I'm going to get rid of that and let me fix it okay now let's reload it uh let me go to the homepage okay now it it worked there is no error and and the data has been loaded so now we can uh style it we have multiple options to style it we can use the inline style CSS files or css modules or tailin css so let's start from the inline style so let's say here you want to add a border around the every user for that let's go to the page. ESX and here I will add style and add width 100 pixels and height 100 pixels and Border 1 pixel solid light gray okay this is how it is looking the width is too small so we have to increase the width to maybe 300 pixels and let's add margin bottom below every box save it and height is also too small so let me increase it to 70 170 all right so this is one way to design it uh second option is that you can create a variable let Styles is equal to and cut all of these Styles and pass the Styles variable here and put the object here all right it will still work the second option is that uh you will create the external CSS file so here let me create a file like home. CSS and now I will cut all of these styles from here and let's get rid of this and let's remove this as well and now in the home CS I will paste my Styles we have to fix some things like remove the double codes also we have to add semicolon instead of comma also we have to add the red rapper user okay we have added the selector and this has to have the dash in the name okay great now let's add this class to every user for that here I will add the class user now we need to import that CSS file import home. CSS save it and now you can see that styles are still being visible and these are working the second approach is that but before showing that uh third approach uh let me show you the class name in the inspect element here you can see the class is user okay so but another approach is that the CSS modules so in order to CSS modules you have to put module at the end of the file name and now here let's import module. CSS and here you need to get them in a variable like import styles from this okay now copy the style variable and here instead of putting the uh hardcoding the class name you will just use you user uh styles. uh user okay save it now you would notice that it is still working but this time if you uh look at this class name this class name is very unique so in this way you don't have to worry about making the class names unique for every component because even if you use the same class names or selectors it will never conflict with the styles of other uh components so this uh this is a very good uh Way by using modules in this way you you don't have to worry about making your class names unique okay after that another option is that if you don't want to use CSS we have the option Tailwind if you have SE opt if you opted in for the Tailwind while installation process of nextjs you can directly use a Tailwind as well so here instead of using these Styles I will just add this and here I will add uh Stalin CSS classes like a w Dash and here you can add maybe 300 pixels and H - 200 pixels and MB 10 and here you can add border and Border gray 40 or 50 and here you can add border two let's remove this one and let's justest reload it by the way these are not working the reason that remember we commented out the Tailwind CSS uh in here so now if you reload it you will see that everything is working again okay so let's go back to our page and here let me make it darker that and you can see now it is working very well so this is how you can use tailin CSS classes and if you don't like in this way just cut it from here and add something again like styles. users and in the home. module you can delete all of these and use apply and put all of th those Tailwind CSS classes like that and it will still work reload it and if you inspect element you would notice that they have the unique class name and but they are still working with the help of the tail CSS okay uh next is the deploying your project so you can deploy your project uh to anywhere uh versal is very easy to use to for for the deployment so we will use the versal in this case okay now I'm going to create my new repo because that is the requirement to deploy on the versal uh so that is the convenient way so here in the repository name I will add anything temporary next GS so so that I could delete it after it is done so now once I do that click on the create repository you can make it private as well if you want to and once that is done copy the URL and open the editor open the root directory of your project and I will type get remote add origin this okay the origin has been added now let me create a commit git add git commit DM so I will add a commit message files press enter now I will push it get push or origin main with that if you reload it you will notice that it is deployed here on the GitHub but now we have to set up versal so go to the versal cck click on the add new click on the project and here you will click on click on the connect with GitHub okay once you open that uh you will see the list of repositor in your GitHub account this is the one that we created 2 minutes ago so click on the import button and here you can make CH want if you want to make changes you can make ches here but most of the time you don't have to make any change here so just click on the deploy and give it some time and it would be deployed after some time okay you can see that it has been deployed and it is showing the preview as well so if you click on that continue to the dashboard it will show you your project and from here you will see a button here visit click on that it will open your website okay you can see that your website has been deployed so you can you saw that how easy it was to deply your next GS project to the versal so as now it is is connected with the versal so whenever you make any change in your project and if you commit and deploy it to the GitHub again it will automatically deploy those changes to the versal so you don't have to touch the versal again all right I think that's all for now for this video I hope that this video was useful for you if this video helped you in any way then please don't forget to subscribe to my channel and hit that Bell icon to get notified for my upcoming videos and please like and share this video if you have any questions or feedback or suggestions then please leave them in the comment section below and I will do my best to reply them as soon as possible thanks for watching and see you next time
Info
Channel: AyyazTech
Views: 1,912
Rating: undefined out of 5
Keywords: APIRequest, CSSModules, CustomComponents, Deployment, ErrorBoundary, ErrorHandling, ExternalCSS, GithubConnect, HandlingErrors, InlineStyles, NextJS, ServerActions, StylingUI, TailwindCSS, Versal
Id: GgvE5fkIs9o
Channel Id: undefined
Length: 23min 35sec (1415 seconds)
Published: Sat Mar 02 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.