In this lesson, we're going to look at how to use API request in React
Unlike Fetch, Axios is not readily available, so we'll have to install it. Let's go back to our VS Code and open the terminal. Make sure you're inside the client directory, and type:
Axios supports TypeScript so we don't have to install the
@typesmodule as dev dependency.
Now let's start our development server by typing:
Also make sure that our server is running, so that we can fetch the data from our API. Let's open another terminal and type:
Now that our servers are running, let's go inside the client directory and open the
App.tsx file. Let's import axios from axios. We want to make the API request as soon as the page first renders, and for that we need to use hooks; useEffect hook to make the request and useState hook to store the data. So, let's import useState and useEffect from React.
Make sure you're using useState hook on top of the function. useState is a hook which returns 2 values — first one is the variable where we want to store the data, and second one is a function which is used to set the data, both of which are inside an array separated by a comma. It's a convention to make your function start with set, so we are naming our variable, courses, and we will name our function, setCourses. It follows camel case. Then for the useState hook which takes initial value as a parameter, we are going to provide an empty array as initial value which means that before making the API request, our courses variable will be an empty array.
To make a request to our server, we are going to use useEffect hook. It takes a callback function as the first parameter. This is where we are going to make the API request. As a second parameter, it takes a dependency.
So what does a dependency do? If we leave it as an empty array, the callback function will only run once, that is, when the page first mounts. 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, not even an empty array? In this case, It will re-run the function whenever the page re-renders. I hope it makes sense. We want to run this only once, so we will provide an empty array as the second parameter.