React Hooks tutorials for beginners-5

Welcome to part-5 of the series. You can find part-4 here. We will look into doing API calls with useEffect in this part.

Fetching data with useEffect

In this part, we will fetch data from an API endpoint. We will first install the axios package to do api call. Open the terminal and run below command.

npm install --save axios

Now, create a new file DataFetching.js inside the components folder. Inside useEffect we are using axios to hit the API endpoint, which is returning a promise.

After this include the component in App.js file.

Now, in localhost we can see the data been received in the console.

Now, we will set the state to show the posts on the screen. We will just pass res.data to setPosts.

Now, we will get the posts title displayed, but we get an issue and that is the infinite call to the api endpoint.

We can fix it easily, because we want the data to be fetched only once and mimic the componentDidMount lifecycle method. As from the earlier part, we do this my specifying an empty array as the second parameter.

Now, back to localhost and our issue is resolved.

We will now learn how to fetch individual posts through useEffect now.

For this we need to hit the endpoint like https://jsonplaceholder.typicode.com/posts/1, where each number represent a post.

Now, create a new file DataFetching2.js inside the components folder. It is mostly similar to DataFetching.js, but have a input box which contains it’s set of state.

We are also hitting a different API end point and instead of passing an empty array as second parameter, we are passing id. We are passing id, because the useEffect should trigger if the state variable id is changed. The id is changed through the input box.

Now, include the DataFetching2 in App.js file.

Now, in localhost, we will see the single post title and also the new title, if we change it from the input box.

This completes part-5 of the series. You can find part-6 here.

You can find the code for the same in this github repo.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Nabendu Biswas

Nabendu Biswas

590 Followers

Founder TWD, JavaScript & ReactJS Trainer, Youtuber, Blogger