How to do API calls in React Native with Axios

Last Updated on December 13, 2020.

You can consume APIs in react native using 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 price 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 axios library using the command given below:

npm install axios

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

Class based component

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

const URL = 'https://api.coindesk.com/v1/bpi/currentprice.json';
class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      inDollars: '',
      inEuro: '',
      inPounds: '',
    };
  }

  componentDidMount() {
    axios.get(URL).then(response => response.data)
      .then((data) => {
        this.setState({
          inDollars: data.bpi.USD.rate,
          inEuro: data.bpi.EUR.rate,
          inPounds: data.bpi.GBP.rate,
        });
      });
  }

  render() {
    const { inDollars, inEuro, inPounds } = this.state;
    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;

Function based component

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:

If you have any doubts, then please use the comment section given below.

1 thought on “How to do API calls in React Native with Axios”

  1. Pingback: How to use Async and Await with Axios and React Native - REACT NATIVE FOR YOU

Leave a Reply

%d bloggers like this: