Learning React: APIs with Fetch & Axios

Unlike Gretchen from Mean Girls, React really IS going to make fetch 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…


This content originally appeared on DEV Community and was authored by Sarah Thompson

Unlike Gretchen from Mean Girls, React really IS going to make fetch 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 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: &)
Pokemon API has a handful of different queries you can make for Pokemon names, powers, types, and pictures.

Fetch()

The fetch() 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 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 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!


This content originally appeared on DEV Community and was authored by Sarah Thompson


Print Share Comment Cite Upload Translate Updates
APA

Sarah Thompson | Sciencx (2021-05-26T20:24:58+00:00) Learning React: APIs with Fetch & Axios. Retrieved from https://www.scien.cx/2021/05/26/learning-react-apis-with-fetch-axios/

MLA
" » Learning React: APIs with Fetch & Axios." Sarah Thompson | Sciencx - Wednesday May 26, 2021, https://www.scien.cx/2021/05/26/learning-react-apis-with-fetch-axios/
HARVARD
Sarah Thompson | Sciencx Wednesday May 26, 2021 » Learning React: APIs with Fetch & Axios., viewed ,<https://www.scien.cx/2021/05/26/learning-react-apis-with-fetch-axios/>
VANCOUVER
Sarah Thompson | Sciencx - » Learning React: APIs with Fetch & Axios. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/05/26/learning-react-apis-with-fetch-axios/
CHICAGO
" » Learning React: APIs with Fetch & Axios." Sarah Thompson | Sciencx - Accessed . https://www.scien.cx/2021/05/26/learning-react-apis-with-fetch-axios/
IEEE
" » Learning React: APIs with Fetch & Axios." Sarah Thompson | Sciencx [Online]. Available: https://www.scien.cx/2021/05/26/learning-react-apis-with-fetch-axios/. [Accessed: ]
rf:citation
» Learning React: APIs with Fetch & Axios | Sarah Thompson | Sciencx | https://www.scien.cx/2021/05/26/learning-react-apis-with-fetch-axios/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.