fetching data from remote server

ref – https://javascript.plainenglish.io/from-fetch-api-to-useeffect-and-axios-the-many-ways-of-fetching-api-data-367757ea5ac6

fetch( ) — the Fetch API method

A few months ago, I was primarily fetching data in JavaScript and React using the fetch() API. It’s the easiest, and most readily available way to get data, since it is built into most modern browsers (with exception of Internet Explorer as of me writing this blog).The fetch() API

It calls the fetch() method, which takes in one argument, the resource. This is the path to the data you want to fetch. This can be your API data such as a link, or a request object. It then returns a promise, which contains a response object. Since the response that we get back is just an HTTP response, we append the json() method to the response, so that we get back the actual JSON formatted data as our response.

On a side note, a major disadvantage of the fetch API is handling errors.

In my example above, I didn’t factor my code to handle errors. And this can be bad, because even if the url sends me an 404 error (meaning page not found), we still send that as a response without breaking our code. I will show you how to handle fetch errors in the next two methods below.

fetch with useEffect

Since hooks are becoming more common in how we use React, the hooks way of fetching data is using the useEffect method. The Effect Hook adds the ability to do the same function as componentDidMount in our first example, or to perform other side effects, but in a function component.

As the example above shows, we used a class component. The useEffect() lets us use componentDidMount, componentDidUpdate, componentDidUnmount that we would in classes, in function components, but it’s all packaged into a single API — useEffect!

If our response is okay, we go ahead and return that response. However, if our response isn’t okay, say there’s an error in our response, we throw the response as an error, that our .catch callback will handle.
Then in the .finally callback, we use it as a function that will show us our data or an error, should our response be okay or not.

Axios

Axios is an open-source library for making data requests. In order to use axios, you have to first install it as it does not come built in like fetch or useEffect in React. You can install it with package managers like yarn or npm.

Axios supports all modern browsers, even Internet Explorer.
You can also use it in vanilla JavaScript, React, Vue.js, and Angular.

Axios also has better error handling and performs automatic transformations. It lets us cut down a lot of our code!

We were able to cut down the response because Axios handles the first callback where we check to see if a response is okay and give us an error if it’s not.