How to do API calls in React Native with Axios

You can consume APIs in react native using the Axios library. You can use either Axios or Fetch API to fetch data from third-party APIs. In this example, I am using Axios to call APIs.

In the example below, I am using free coindesk API which gives Bitcoin prices in different currencies. The API link is https://api.coindesk.com/v1/bpi/currentprice.json and the HTTP method to be used is ‘get’.

First of all, install the Axios library using any of the commands given below.

yarn add axios

or

npm install axios

Now, copy and paste the following code into App.js.

import React, {useState, useEffect} from 'react';
import axios from 'axios';
import {View, Text} from 'react-native';

const URL = 'https://api.coindesk.com/v1/bpi/currentprice.json';
const App = () => {
  const [inDollars, setInDollars] = useState('');
  const [inEuro, setInEuro] = useState('');
  const [inPounds, setInPounds] = useState('');

  useEffect(() => {
    axios
      .get(URL)
      .then(response => response.data)
      .then(data => {
        setInDollars(data.bpi.USD.rate);
        setInEuro(data.bpi.EUR.rate);
        setInPounds(data.bpi.GBP.rate);
      });
  });

  return (
    <View style={{justifyContent: 'center', alignItems: 'center'}}>
      <Text style={{color: 'black'}}>Price of 1 Bitcoin</Text>
      <Text>USD: {inDollars}</Text>
      <Text>EURO: {inEuro}</Text>
      <Text>GBP: {inPounds}</Text>
    </View>
  );
};

export default App;

That’s it, the output will be as given in the screenshot below:

react native axios example

That’s how you use Axios in react native. If you have any doubts, then please use the comment section given below.

Similar Posts

One Comment

Leave a Reply