Make HTTP GET Requests With Axios

The most common way for frontend programs to communicate with servers is through the HTTP protocol. If you’re used to vanilla JavaScript, then you’re probably familiar with the fetch() API which allows you to fetch resources and make HTTP requests. In …


This content originally appeared on DEV Community and was authored by Rodrigo Rojas

The most common way for frontend programs to communicate with servers is through the HTTP protocol. If you're used to vanilla JavaScript, then you're probably familiar with the fetch() API which allows you to fetch resources and make HTTP requests. In this example I'm going to walk you through on how to use axios in React to make an HTTP GET request. Further on I'll walk us through how to make POST, DELETE, and even PUT requests. For now, let's stick to GET. Let's GET-er-done! (ok I'll stop).

Get er done

Couldn't help myself

Let's first create a db.json file in the root directory of your project in order to use the JSON Server. For this example, I'm using data for a phonebook app I worked on.

{
  "people": [
    {
      "name": "Hannah Rickard",
      "number": "06-51-99-56-83",
      "id": 1
    },
    {
      "name": "Hyun Namkoong",
      "number": "10987654",
      "id": 2
    },
    {
      "name": "Courtney Martinez",
      "number": "3691215",
      "id": 3
    }
  ]
}

Next, install the JSON server by running:

npx json-server --port 3001 --watch db.json

Note that the json-server runs on port 3000 by default, but since projects created with create-react-app reserve port 3000, we need to define an alternate port.

The idea will be to save future contacts to the server, which in this case means saving to the json-server. The React code fetches the contacts from the server and renders them to the screen. Once a new note is added to the app, the React code will persist it to memory.

Let's install axios:

npm install axios

package.json

Axios will now be added to the other dependencies

Let's tweak the scripts part of the package.json file so we don't have to type as much bc we're lazy.

Scripts

Nice and short

Now all you have to type to start the json-server is:

npm run server

Nice! We're now ready to use axios. Open up two terminal windows, one to keep the json-server running, and the other for react-app.

The axios library can now be imported in just like any other library in React. With a good ol' import statement.

import React, { useState, useEffect } from 'react;
import axios from 'axios';

For this example I'm gonna assume you know about React State Hooks, and if not, I'll make a mental note for another blog ? .

However, effect hooks will be exceptionally useful in our case becauuuse as the doc states:

The Effect Hook lets you perform side effects in function components. Data fetching, setting up a subscription, and manually changing the DOM in React components are all examples of side effects.

Let's now dive in to our app.

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const App = () => {

  // our state hook
  const [people, setPeople] = useState([])

useEffect(() => {
  console.log('effect')
  axios
    .get('http://localhost:3001/people')
    .then(response => {
      console.log('promise fulfilled')
      setPeople(response.data)
    })
}, [])
 console.log('render', people.length, 'people')

//...

Our faithful console.log gives us some hints as to what is happening here by clarifying the progression of the execution. The console prints out the following:

render 0 people
effect
promise fulfilled
render 3 people
  • The body of the function defining the component is executed first thus printing out render 0 people. Meaning data hasn't been fetched yet.
  • Our useEffect function is executed immediately after rendering.
  • In result, effect is printed followed by axios.get fetching our data.
  • promise fulfilled is registered inside our event handler for the operation and printed.
  • Lastly, the setPeople function changes our state thus triggering a re-render resulting in render 3 people being printed to the console. Meaning we've successfully fetched our data!

Let's refactor our effect hook:

const hook = () => {
    axios.get('http://localhost:3001/people')
    .then(response => {
      setPeople(response.data)
    })
  }
  useEffect(hook, [])

This way we can now see that useEffect() takes two parameters. Firstly, a function, or the effect itself. Once again, the doc is our friend:

By default, effects run after every completed render, but you can choose to fire it only when certain values have changed.

According to this, the effect is always run after the component has been rendered. In our case, we only want to execute the effect with the first render.

The second parameter of useEffect() is used to specify how often the effect is run. If the second parameter is an empty array [], the effect will only run with the first render.

Noice gif

You can fetch with axios now!

Well done! We've successfully performed a GET request with axios. We'll talk about sending data to the server in another post.

Resources


This content originally appeared on DEV Community and was authored by Rodrigo Rojas


Print Share Comment Cite Upload Translate Updates
APA

Rodrigo Rojas | Sciencx (2021-05-21T19:23:13+00:00) Make HTTP GET Requests With Axios. Retrieved from https://www.scien.cx/2021/05/21/make-http-get-requests-with-axios/

MLA
" » Make HTTP GET Requests With Axios." Rodrigo Rojas | Sciencx - Friday May 21, 2021, https://www.scien.cx/2021/05/21/make-http-get-requests-with-axios/
HARVARD
Rodrigo Rojas | Sciencx Friday May 21, 2021 » Make HTTP GET Requests With Axios., viewed ,<https://www.scien.cx/2021/05/21/make-http-get-requests-with-axios/>
VANCOUVER
Rodrigo Rojas | Sciencx - » Make HTTP GET Requests With Axios. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/05/21/make-http-get-requests-with-axios/
CHICAGO
" » Make HTTP GET Requests With Axios." Rodrigo Rojas | Sciencx - Accessed . https://www.scien.cx/2021/05/21/make-http-get-requests-with-axios/
IEEE
" » Make HTTP GET Requests With Axios." Rodrigo Rojas | Sciencx [Online]. Available: https://www.scien.cx/2021/05/21/make-http-get-requests-with-axios/. [Accessed: ]
rf:citation
» Make HTTP GET Requests With Axios | Rodrigo Rojas | Sciencx | https://www.scien.cx/2021/05/21/make-http-get-requests-with-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.