Learning React: APIs with Fetch & Axios
Tags: fetch, react, webdev, javascript
Published: 2021-05-26 20:24:58


Unlike Gretchen from Mean Girls, React really IS going to make [fetch](https://reactjs.org/docs/faq-ajax.html) happen.

Whether you like using functional components or class components, if your app is big enough you're likely needing to get data from an API. 

If you're just learning right now and need an API to practice on I've got a two suggested free ones I've liked using:

 **[Trivia API](https://opentdb.com/api_config.php)** this has a lot of parameter options, although a lot of the data returned needs to be cleaned of character entities before you display it (ex: &amp;)
 **[Pokemon API](https://pokeapi.co/)** has a handful of different queries you can make for Pokemon names, powers, types, and  pictures.

##Fetch()

The [fetch()](https://levelup.gitconnected.com/how-to-make-http-requests-with-fetch-api-be018730811f) call takes in two argument, your api url parameter, like `fetch("https://pokeapi.co/api/v2/pokemon/1")`, is one. The other one is the init object which can contain headers, body, credentials, and any other piece of information.

As basic fetch() call looks like this:

```
fetch('https://pokeapi.co/api/v2/pokemon/1')
  .then(response => response.json())
  .then((results) => {console.log(results)});
```

You should be putting your [api](https://reactjs.org/docs/faq-ajax.html) fetch() calls in your 'componentDidMount' lifecycle method if you're using a class component, and if you're using a functional component you should make sure your `useEffect` hook will also call on render by appending an empty array to it.

Fetch returns a promise that points to the response from the request that was made to the API no matter if the request is successful or not. This response is just a HTTP response and not JSON. In order for you to get the JSON body content of the response, you need to use the json() method on the response.

```
     fetch(powersUrl).then(response => response.json()).then(
         (result) => {
             this.setState({
                 powerInfo: result
             });
         },
         (error) => {
             this.setState({
                error
             });
          }
     )
```

Instead of using a `.catch()` block for errors, with fetch() we are using a `(error)` so that it doesn't swallow the exceptions from any actual bugs that could be in the components. 

A request made with Fetch will only be rejected if there is a  network failure or if something is preventing the request from completing - if it is a 4xx or 5xx type code it will update the `ok` status.

To add variable query params you can encode them straight into the URL.

```
fetch(`https://pokeapi.co/api/v2/pokemon?limit=${encodeURIComponent(data.limt)}`)
.then(res => res.json())
.then( ....
```

This fetch() function lets you to make HTTP requests with standard HTTP verbs like `GET`, `POST`, `PUT`, and `DELETE`. You can append other needed data to the fetch() like method, headers, and body into the init object 

```
 fetch(userURL , {
      method: 'GET',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
    })
      .then((resp) => resp.json())
     .then(  ......
```


##Axios()
Axios is another [tool](https://www.smashingmagazine.com/2020/06/rest-api-react-fetch-axios/) we can use to handle API calls. It is a lightweight promise based HTTP client for browsers and also for node.js. 

```
import axios from 'axios'
```
You need to install it with npm and add it to your package.json, then you'll import it at the top of your file. Axios takes two inputs, the URL of the endpoint you're trying to hit and an object that contains all of the properties you want to send.

```
    axios.get(monsterUrl).then(
        res => {
            var monsterChart = []
            monsterChart.push(<div> {{res.pokemon}}</div>)
            updateMonster(monsterChart)
            }
        ).catch(
            .... )
    }
```

You can also format it like this:
```
axios({
      method: 'post',
      url: 'https:/coolAPI.com/api/cool',
      data: {
            email: 'myTest@example.com',
            password: test1234
      }
})
```
There's lots more to dig into, but these are two solid part to practice on!