How to make an HTTPS request by Axios library in React Native.

The internet boasts a vast array of resources hosted on different servers. For you to access these resources, let’s say your browser or mobile device needs to be able to send a request to the servers and display the resources for you. HTTPS (Hypertext Transfer Protocol), is the underlying format that is used to structure requests and responses for effective communication between a client and a server. The message that is sent by a client to a server is what is known as an HTTPS request. When these requests are being sent, clients can use various methods like POST, GET, DELETE, etc...

How Do HTTPS Requests Work?

HTTPS requests work as the intermediary transportation method between a client/application and a server. The client submits an HTTPS request to the server, and after internalizing the message, the server sends back a response. The response contains status information about the request like the photo below.

HTTPS request

In this article, we gonna use The News API to get list of latest news.
first of all, you have to register on that website to get an api_key so without this key you’ll not be able to make a request.

Create and Running your React Native application:

Step 1: Create a React Native app

$ npx react-native init your_project_name

If we use Yarn as a package manager we will add the following lines:

$ npm install -g yarn
$ yarn global add react-native-cli
$ react-native init sample

Step2: add the Axios library to the project:

first, we have to change the directory to project path in our device:

$ cd your_project_path

after that for the users who are using the NPM package manager should add the following line in the terminal:

$ npm install axios

for Yarn package manager users should add the line:

$ yarn add axios

Step3: Running the project

Using NPM as a package manager:

// IOS Platform
$ npx react-native run-ios
// Android Platform
$ npx react-native run-android

Using Yarn as a package manager:

// IOS Platform
$ yarn ios
// Android Platform
$ yarn android

we will see the initial following screen:

Then we have to create a custom component and name it NewsCard.js

it contains the title, author, image, and description of the news and we will give him some StyleSheet properties like this:

NewsCard.js

Making Axios get request to fetch a list of news:

In order to fetch News from a URL, we can pass the URL to fetch:

axios.get(baseURL);

Get method also takes an optional second argument that allows us to customize the HTTPS request. We may want to specify params as a JSON object when there are query parameters in the URL like our example:

axios.get(baseURL, {
params: {
country: 'us',
apiKey: 'aa6a097fb9fb4509958fdabd1942e6d1',
},
})

Networking is an asynchronous operation. Get method will return a Promise that makes it straightforward to write code that works in an asynchronous manner:

axios.get(baseURL, {
params: {
country: 'us',
apiKey: 'aa6a097fb9fb4509958fdabd1942e6d1',
},
})
.then(async function (response) {
//do anything you want in our example we set the news
setNews(response.data);
})

The last thing we have to take into consideration is catching the error if the response has failed by using the catch() method like this:

axios.get(baseURL, {
params: {
country: 'us',
apiKey: 'aa6a097fb9fb4509958fdabd1942e6d1',
},
})
.then(async function (response) {
//do anything you want in our example we set the news
setNews(response.data);
})
.catch((error) => {
//do whatever you want let's say print the error in the console.
console.log(error)
});

After we have finished the networking operations we would create the main screen which name is News.js, it will contain FlatList inside this component we will render the news items data as useState that have just received from the response like this:

const renderNewsList = ({item}) => <NewsCard item={item} />;return (
<SafeAreaView>
<View>
<FlatList
data={news.articles}
keyExtractor={(item, index) => 'key' + index}
renderItem={renderNewsList}
/>
</View>
</SafeAreaView>

In order to track component changes when making a request, we should create news as a useState hooks variable and calling the setNews function when we receive a response successfully.

const [news, setNews] = useState([]);
.then(async function (response) {
setNews(response.data);
})

When we running the app after rendering the components we should use useEffet hooks and inside it, we will make the request to reflect the changes on the screen like this:

useEffect(() => {
getNewsFromAPI();
}, []);
function getNewsFromAPI() {
axios.get(baseURL, {
params: {
country: 'us',
apiKey: 'aa6a097fb9fb4509958fdabd1942e6d1',
},
})
.then(async function (response) {
setNews(response.data);
})
.catch((error) => console.log(error));
}

We will show the result after we attached the full News.js file :

News.js
Results

Conclusion

In this article, we have learned how to implement restful API’s using GET() and Axios methods in our React native app example. We also have learned how to handle responses from these methods and use their data in the app.

I have more than one year of experience in programming Android applications by using Java and Kotlin as a programming language and now I am learning React.