React Axios Get

Posted on  by admin

Below is a quick set of examples to show how to send HTTP GET requests from React to a backend API using the axios HTTP client which is available on npm.

Other HTTP examples available:. React + Axios: POST, PUT, DELETE. React + Fetch: GET, POST, PUT, DELETE. Vue + Axios: GET, POST.

Vue + Fetch: GET, POST. Angular: GET, POST, PUT, DELETE. Blazor WebAssembly:GET, POST. Axios: GET, POST, PUT, DELETE. Fetch: GET, POST, PUT, DELETE.

With the npm CLI: npm install axios.

Conclusion

With the yarn CLI: yarn add axios. This sends an HTTP GET request from React to the npm api to search for all react packages using the query q=react, then assigns the total returned in the response to the component state property totalReactPackages so it can be displayed in the render() method.

Example React component at https://stackblitz.com/edit/react-http-get-request-examples-axios?file=App/GetRequest.jsx.

Step 1 — Adding Axios to the Project

The componentDidMount() Function

This sends the same GET request from React using axios, but this version uses React hooks from a function component instead of lifecycle methods from a traditional React class component.

The useEffect React hook replaces the componentDidMount lifecycle method to make the HTTP GET request when the component loads.

The second parameter to the useEffect React hook is an array of dependencies that determines when the hook is run, passing an empty array causes the hook to only be run once when the component first loads, like the componentDidMount lifecyle method in a class component.

For more info on React hooks see https://reactjs.org/docs/hooks-intro.html. Example React hooks component at https://stackblitz.com/edit/react-http-get-request-examples-axios?file=App/GetRequestHooks.jsx.

GET request using axios with set HTTP headers

This sends the same GET request from React using axios, but this version uses an async function and the await javascript expression to wait for the promises to return (instead of using the promise then() method as above).

Example React component at https://stackblitz.com/edit/react-http-get-request-examples-axios?file=App/GetRequestAsyncAwait.jsx.

  1. This sends a GET request from React using axios to an invalid url on the npm api then assigns the error message to the errorMessage component state property and logs the error to the console.
  2. Example React component at https://stackblitz.com/edit/react-http-get-request-examples-axios?file=App/GetRequestErrorHandling.jsx.
  3. This sends the same GET request again from React using axios with a couple of headers set, the HTTP Authorization header and a custom header My-Custom-Header.
  4. Example React component at https://stackblitz.com/edit/react-http-get-request-examples-axios?file=App/GetRequestSetHeaders.jsx. I am building a simple app that is expected to render the data from http://vk-consumer:8003/v1/entity endpoint.
  5. Users should be able to access the links and explore further http://vk-consumer:8003/v1/entity/countries. This is what I have to test if I can access the endpoint, but when I run this, I get a Module not found: Error: Can't resolve 'url' in /node_modules/axios/lib/adapters'.

Displaying our message

I also don't know if I am getting the headers correctly.

  1. I have two keys and values that I need to be able to access the endpoints:.
  2. Any idea how i can get this to render the data from the endpoint?
  3. In this tutorial, I will show you how to fetch data from an API to your react app.

It doesn’t matter what backend technology you are using (i.e Nodejs, WordPress, etc) you can fetch data from the backend using API and axios to your react app.

I won’t explain what is an API, What is Axios because you can google it 😁 😁. So let us start the tutorial.

JsonPlaceHolder for dummy API. First, we need to create a react app.

You can follow my previous tutorial Getting Started with ReactJS to create a simple hello world app.

After that open your terminal and install axios. Now we will create an instance for baseURL. This instance is created so that we don’t have to manually change the base URl of the API in each component.

GET request using axios with React hooks

So to create the instance we need to go our app src folder and create a file name axios.js.

Now open your project inside your favorite IDE and paste this inside your newly created axios.js file. Note: change https://jsonplaceholder.typicode.com/ with your own API base URL.

Now we will create our components folder to put all our components in one place. Now in your src folder create a new folder name components and inside that create another folder name users. Now create a file users.js inside your users folder and create the react class component by pasting this.

Now import your users.js file in your app.js file inside your src folder. Now import axios from your newly created axios.js file from your src folder to the component. Now it’s time to add a class constructor and assigns the initial state Users : [].

Now we will create a function to call our users data from an API using axios to our component.

GET request using axios with error handling

Create a function name getUsersData after your class constructor and paste this inside your function.

Note: you need to call getUsersData function inside your componentDidMount lifecycle method by insertingthis.getUsersData(). Your users.js will look something like this.

Now run your app by typing npm startin your terminal and check the browser console.

You will see an array of objects inside your console. Hola 😎 we have successfully called our data from an API to our react app using axios. Now it’s time to print the data in our app.

For this, we will use the javascript mapand arrowfunction to loop through our array of objects. Just after your console.log(data) paste this.

Now call your users data using this.state.users inside return to print in your app. Finally, your users.js file will look like this.

Step 4 — Making a DELETE Request

Refresh your browser and tada 😱 all your data is printed.

Thanks for reading. Here is the live example and GIT repository for that.

Many projects on the web need to interface with a REST API at some stage in their development.

Axios is a lightweight HTTP client based on the $http service within Angular.js v1.x and is similar to the native JavaScript Fetch API.

Axios is promise-based, which gives you the ability to take advantage of JavaScript’s async and await for more readable asynchronous code.

The Axios Code — Making the HTTP GET request

You can also intercept and cancel requests, and there’s built-in client-side protection against cross-site request forgery.

In this article, you will see examples of how to use Axios to access the popular JSON Placeholder API within a React application.

To follow along with this article, you’ll need the following:. Node.js version 10.16.0 installed on your computer.

To install this on macOS or Ubuntu 18.04, follow the steps in How to Install Node.js and Create a Local Development Environment on macOS or the Installing Using a PPA section of How To Install Node.js on Ubuntu 18.04.

A new React project set up with Create React App by following the How to Set up a React Project with Create React App tutorial.

It will also help to have a basic understanding of JavaScript, which you can find in the How To Code in JavaScript series, along with a basic knowledge of HTML and CSS. This tutorial was verified with Node.js v16.13.1, npm v8.1.4, react v17.0.2, and axios v0.24.0.

In this section, you will add Axios to a React project you created following the How to Set up a React Project with Create React App tutorial.

Importing the libraries we need — React & axios

To add Axios to the project, open your terminal and change directories into your project:.

Then run this command to install Axios:. Next, you will need to import Axios into the file you want to use it in. In this example, you create a new component and import Axios into it to send a GET request.

Inside your React project, you will need to create a new component named PersonList. First, create a new components subdirectory in the src directory:.

In this directory, create PersonList.js and add the following code to the component:.

First, you import React and Axios so that both can be used in the component. Then you hook into the componentDidMount lifecycle hook and perform a GET request.

You use axios.get(url) with a URL from an API endpoint to get a promise which returns a response object. Inside the response object, there is data that is then assigned the value of person.

You can also get other information about the request, such as the status code under res.status or more information inside of res.request.

Add this component to your app.js:. Then run your application:. View the application in the browser.

Simple GET request using axios

You will be presented with a list of 10 names. In this step, you will use Axios with another HTTP request method called POST. Inside your React project, you will need to create a new component named PersonAdd.

Create PersonAdd.js and add the following code to create a form that allows for user input and subsequently POSTs the content to an API:. Inside the handleSubmit function, you prevent the default action of the form.

Then update the state to the user input. Using POST gives you the same response object with information that you can use inside of a then call. To complete the POST request, you first capture the user input.

Then you add the input along with the POST request, which will give you a response. You can then console.log the response, which should show the user input in the form.

Add this component to your app.js:. Then run your application:. View the application in the browser. You will be presented with a form for submitting new users.

Check the console after submitting a new user. In this example, you will see how to delete items from an API using axios.delete and passing a URL as a parameter. Inside your React project, you will need to create a new component named PersonRemove.

Step 6 — Using async and await

Create PersonRemove.js and add the following code to delete a user:. Again, the res object provides you with information about the request.

You can then console.log that information again after the form is submitted. Add this component to your app.js:. Then run your application:. View the application in the browser. You will be presented with a form for removing users.

In this example, you will see how you can set up a base instance in which you can define a URL and any other configuration elements.

Create a separate file named api.js:. Export a new axios instance with these defaults:.

Once the default instance is set up, it can then be used inside of the PersonRemove component. You import the new instance like this:.

Because http://jsonplaceholder.typicode.com/ is now the base URL, you no longer need to type out the whole URL each time you want to hit a different endpoint on the API. In this example, you will see how you can use async and await to work with promises.

The await keyword resolves the promise and returns the value. The value can then be assigned to a variable.

In this code sample, the .then() is replaced. The promise is resolved, and the value is stored inside the response variable. In this tutorial, you explored several examples on how to use Axios inside a React application to create HTTP requests and handle responses.

If you’d like to learn more about React, check out the How To Code in React.js series, or check out the React topic page for more exercises and programming projects.

This actually took me longer than I expected when I was still learning how to do this.

Installing axios from npm

As such, this article is meant to serve as the documentation that I wished I had when I was still learning how to make HTTP requests in React.

Let’s dive right in. I created this simple endpoint using npoint.io — a free JSON storage service. If we make a GET request to this url, we will get:. If you want, you can paste this url into your browser, and you should see this JSON string in your browser too.

Our aim today would just be to display this message on our React application’s home screen. A completely blank page that displays the message from our endpoint.

(No hardcoding of this message allowed).

Axios is the library that we are using to make the HTTP GET request. Yes, there are other libraries available that can do the same thing, but this is simple enough and works well enough for me.

To check if axios has been installed without any issue, simply import it and check if an error message appears.

When you run your application and there’s no error, axios has been installed without a problem. Here, each component has a state — essentially some stored data when our Component class is created. To keep things simple, our state here has the variable message with a value "default value".

To show the message from our state, we can use this syntax this.state.message in our HTML portion that we return. By default, if we don’t do any sort of GET request, our app will simply show "default message" instead of "hello world from npoint!!"

This function runs when our app component is mounted (finished loading). The stuff we write inside this function will execute as soon as the stuff inside our components is finished loading.

We will be putting our axios code to make the GET request inside the componentDidMount function. To make the GET request, we call axios.get(url).

Axios HTTP GET Request in React

To handle the response (the JSON thing that we get back after making the GET request), we use the .then method at the back.

Here, response is the entire thing that we get back after making the GET request, and response.data would be the JSON object that we get back.

Step 5 — Using a Base Instance in Axios

In this case, response.data would be :. The this.setState method mutates the state of our component, and is essentially setting message to response.data.message, which happens to be the string "hello world from npoint!!"

After this setState method, our state would be:. Our component state is set to {message: "default message"}. We make the HTTP GET request using the axios library inside the componentDidMount function, and this runs when the component loads.

We get back a response. response.data is {"message": "hello world from npoint!!"