React Native

Making a GET Request in React Native with Axios.

Reading time: < 1 minute
If you want to make an asynchronous GET (ajax) call with React Native, you can’t use jQuery in this environment. Instead, you need to use Axios https://axios-http.com/es/

First, you need to install the dependency by running the following command in the console:

expo install axios

Once installed, you can create the API call. First, import the library:

import axios from "axios";

Now, let’s construct the GET request

axios.get('your_url')
        .then(resp => {
            const response = resp.data;
            alert(JSON.stringify(response));
        })

Making a GET request is as simple as the previous call. Replace your_url with the destination URL.

In the .then(resp => line, you will receive the data. To access the JSON or body of the response, use resp.data and you can handle the data from there.

To add headers, you can do the following

   const config = {
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            "TOKEN": "123456789" 
        }
    };

   axios.get('your_url', config)
        .then(res => {
            const response = res.data;
            alert(JSON.stringify(response));
        })

To handle errors, you can add

.catch(error =>
            console.log('error', error)
        );

The final code will look like this

import axios from "axios";

   const config = {
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            "TOKEN": "123456789" 
        }
    };

   axios.get('your_url', config)
        .then(res => {
            const response = res.data;
            alert(JSON.stringify(response));
        }).catch(error =>
            console.log('error', error)
        );

Leave a Comment