How to use Async and Await with Axios and React Native
In an earlier post, I have written how to do api calls in react native with axios library. In this blog post, I show you how to use async and await in react native with axios.
The following code is from the previous blog post and in that, I use Axios to call API from coindesk to check Bitcoin prices in multiple currencies.
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;
Using async and await make functions asynchronous while handling promises.
Now the full code with async/await using Axios and react native will be as given below:
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('');
const callApi = async () => {
const response = await axios.get(URL);
const data = response.data;
setInDollars(data.bpi.USD.rate);
setInEuro(data.bpi.EUR.rate);
setInPounds(data.bpi.GBP.rate);
};
useEffect(() => {
callApi();
}, []);
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;
Following is the output of the above react native Axios example.
That’s how you use async and await with Axios in react native.