Fetching Data

In this lesson, we're going to look at how to use API request in React

Project Source Code

Get the project source code below, and follow along with the lesson material.

Download Project Source Code

To set up the project on your local machine, please follow the directions provided in the README.md file. If you run into any issues with running the project source code, then feel free to reach out to the author in the course's Discord channel.

This lesson preview is part of the The newline Guide to Fullstack ASP.NET Core and React course and can be unlocked immediately with a single-time purchase. Already have access to this course? Log in here.

This video is available to students only
Unlock This Course

Get unlimited access to The newline Guide to Fullstack ASP.NET Core and React with a single-time purchase.

Thumbnail for the \newline course The newline Guide to Fullstack ASP.NET Core and React
  • [00:00 - 00:17] Now that we know about React and TypeScript, let's use the API endpoints we created to fetch data. Now, to make HTTP requests, we can either use fetch, which is a JavaScript in built function to make Ajax requests.

    [00:18 - 00:26] Ajax stands for asynchronous, JavaScript, and XML. In a nutshell, Ajax allows us to make asynchronous calls to a web server.

    [00:27 - 00:42] It can send and receive information in various formats, including JSON, XML, HTML, and text files. Although fetch can work perfectly fine, it's a bit low-level as compared to XE OS.

    [00:43 - 00:56] In XEOS, you can abort a request, or you can also receive the upload progress if you're uploading a large file. In short, you can intercept the requests and responses and do something with them.

    [00:57 - 01:07] XEOS has many other advantages, which we are going to see as we move along the course. Unlike fetch, XEOS is not readily available, so we'll have to install it.

    [01:08 - 01:16] Let's go back to VS Code and open the terminal. Make sure you're inside the client directory.

    [01:17 - 01:30] Type npm install XEOS. XEOS supports TypeScript, so we don't have to install the @types module as dev dependency.

    [01:31 - 01:43] And now, let's start our development server by typing npm start. Also, make sure that our server is running so that we can fetch the data from our API.

    [01:44 - 01:58] Let's open another terminal and let's go inside the API project. And type .NET watch run.

    [01:59 - 02:16] Now that our servers are running, let's go inside the client directory and open the app.tsex file. Let's import XEOS from XEOS.

    [02:17 - 02:28] We want to make the API request as soon as the page first renders. For that, we need to use hooks, the user effect hook, to make the request and use state hook to store the data.

    [02:29 - 02:40] So, let's import useState and useEffect from react. Make sure you're using the useState hook on top of the function.

    [02:41 - 02:50] UseState is a hook which returns two values. First one is a variable and second one is a function which is used to set the data.

    [02:51 - 02:59] Both of which are inside an array separated by a comma. It's a convention to make your function start with set.

    [03:00 - 03:17] So, we are naming our variable courses and we will name our function set courses. Then the useState hook which takes initial value as a parameter.

    [03:18 - 03:34] We are going to provide an empty array as initial value which means before making the API request, our courses variable will be an empty array. Now, to make a request to our server, we are going to use useEffect hook.

    [03:35 - 03:43] It takes a callback function as the first parameter. This is where we are going to make the API request.

    [03:44 - 03:49] The second parameter it takes is a dependency. So, what does a dependency do?

    [03:50 - 03:59] If you leave it as an empty array, the callback function will only run once. That is when the page first mounts.

    [04:00 - 04:12] If we pass a dependency, let's say, courses, in this case the function will run whenever the value of the courses dependency changes. What if you don't pass any dependency?

    [04:13 - 04:19] Not even an empty array. In this case, it will rerun the function whenever the page re-renders.

    [04:20 - 04:22] I hope it makes sense. We want to run this only once.

    [04:23 - 04:46] So, we will provide empty array as the second parameter. Now, inside this function, let's use xeos.get and provide the courses endpoint which is http localhost 5000/api/courses.

    [04:47 - 04:54] It provides a promise, so let's use then. Then, we'll take the xeos response.

    [04:55 - 05:04] Now, inside the curly brackets, let's use set courses. And pass response.data as the value.

    [05:05 - 05:13] Our response will have a data property which will carry our response from the server. Let's do one thing.

    [05:14 - 05:24] Let's console.log the response as well. To see what it contains.

    [05:25 - 05:31] Before moving to the browser, let's do the cleanup. We don't want to see the basic React page, we want to see our data.

    [05:32 - 05:43] Let's just get rid of everything except the initial div with class name app. Inside the div, let's create an unorder list.

    [05:44 - 05:49] This unorder list will carry our courses. Our courses are stored inside the courses variable.

    [05:50 - 05:58] What we can do is, let's use curly brackets inside the unorder list. Inside this curly brackets, we can use our JavaScript.

    [05:59 - 06:00] Anything we want to. Well, not anything.

    [06:01 - 06:07] The if-else statement doesn't work inside the return statement. But we can use what we are willing to.

    [06:08 - 06:14] I'm talking about the map function. Let's write courses.map.

    [06:15 - 06:24] The map function accepts a callback function. This function is ran for every element inside the object.

    [06:25 - 06:30] As an argument, we get an individual item of the object. Let's call it course.

    [06:31 - 06:42] Second argument is the index it is traversing through. Let's return the list item.

    [06:43 - 06:49] Let's pass index as the key. Otherwise, JavaScript will show us a warning.

    [06:50 - 07:04] Inside our list item, let's see the course ID and the course title. That gives us the error because we haven't given any type to our course.

    [07:05 - 07:15] Which means the properties ID and title don't exist. Let's give our course type any.

    [07:16 - 07:22] It will resolve the issue for now. Let's go back to a browser and see what it shows.

    [07:23 - 07:30] Ah, we see nothing. Let's open our console.

    [07:31 - 07:35] It says our origin is blocked by a course policy. Now, what is a course policy?

    [07:36 - 07:46] Well, it stands for cross origin resource sharing. In simple words, it blocks access of the request which comes from another origin.

    [07:47 - 07:56] As you know, our API server is running on localhost 5000. And our React server is running on localhost 3000.

    [07:57 - 08:04] As they both are different, requests are blocked as per the course policy. Now, how to resolve it?

    [08:05 - 08:10] It's not as complicated as you might be thinking. One simple solution is to install an extension.

    [08:11 - 08:18] I'm using Google Chrome and I have the extension a law course. Just search for it and install it.

    [08:19 - 08:29] Now, once it's installed, click here and refresh the page. And tada!

    [08:30 - 08:40] Our request is successful. Well, this is a workaround, but the recommended fix is to go back to our API project and add course as a service.

    [08:41 - 08:50] This service lets us use an origin we want to make requests from, in our case, localhost 3000. So, let's just set it up.

    [08:51 - 09:01] Go back to the startup file. What we'll do is below the add TB context.

    [09:02 - 09:08] Let's write our course service. Let's write services.add course.

    [09:09 - 09:19] We will give it an option of. Inside the option, let's write opt.add policy.

    [09:20 - 09:30] And let's give our policy the name course policy. Add course method also provides options in the second argument.

    [09:31 - 09:51] So, let's say policy. Inside it, let's write policy.allow any header.allow any method.with origins.

    [09:52 - 10:01] Inside this, we want to provide the URL we want to make requests from. In our case, it is localhost 3000.

    [10:02 - 10:27] By adding the service, we are returning a header, which says that we are allowed to make any request with any header, but it should be from localhost 3000. If you change it to allow any origin, you will be able to make a request from any origin, which we are not going to use.

    [10:28 - 10:38] Even this service is used only in the development phase, as once our application is production ready, requests will be made from the same origin. Alrighty.

    [10:39 - 10:49] Now that we have added the course service, we need to add it to our middleware as well. Giving you a heads up, ordering is very important inside the middleware.

    [10:50 - 10:59] We need to make sure that we are putting it in the correct order. We need to add this just below the app.use routing middleware.

    [11:00 - 11:24] So, let's write app.usecourse and give it a name, course policy that we just created. Make sure the application has restarted.

    [11:25 - 11:29] Now, let's go back to a browser. Let me turn it off first.

    [11:30 - 11:37] Now, let's refresh. And yes, we see the response on the page.

    [11:38 - 11:58] Also, if we see the console, our response has been logged, which has our courses data. We are only displaying the ID and title in the browser, but we can see the rest of the information in the console.

    [11:59 - 12:12] Response also has some extra information, such as the method and the status, but all we are interested in is the data. In the next lecture, let's start working on styling.

    [12:13 - 12:17] We are going to use SAS for styling. Let's install it first in the next lesson.

    [12:18 - 12:43] [ Silence ]