React Hooks tutorials for beginners-5

Image for post
Image for post
Hooks

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.

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
Image for post
Image for post
axios install

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.

Image for post
Image for post
DataFetching.js

After this include the component in App.js file.

Image for post
Image for post
App.js

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

Image for post
Image for post
console

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

Image for post
Image for post
setPosts

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

Image for post
Image for post
Api infinite

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.

Image for post
Image for post
empty array

Now, back to localhost and our issue is resolved.

Image for post
Image for post
Issue 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.

Image for post
Image for post
jsonpolaceholder

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.

Image for post
Image for post
DataFetching2.js

Now, include the DataFetching2 in App.js file.

Image for post
Image for post
App.js

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

Image for post
Image for post
useEffect

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.

Written by

UI Lead- ReactJS, JavaScript and everything in-between.

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